Example #1
0
 public override void FitnessFunction(Population population, GeneticAlgorithm.NextStepDelegate callback)
 {
     this.population = population;
     InitiateNewSimulation();
     simulating = true;
     doneCallback = callback;
 }
Example #2
0
        /* args:
        [0] - a path to a test file
        [1] - a path to a solution file
        [2] - how many times repeat a test
        [3] - whether to save results        
        [4 ...] - GA arguments
        */
        static void Main(string[] args)
        {
            var genAlgArgs = ParseArguments(args);
            if (genAlgArgs == null)
            {
                Console.ReadLine();
                return;
            }

            var ga = new GeneticAlgorithm(genAlgArgs);
            var results = new List<KnapsackSolution>();
            foreach (var knapsack in KnapsackLoader.LoadKnapsacks(args[0], KnapsackLoader.KnapsackPerFile))
            {
                Console.WriteLine($"---Starting knapsack {knapsack.Id}---");
                results.Add(ga.Solve(knapsack));
            }

            if (bool.Parse(args[3]))
                SaveSolutions(results);

            var bestPrices = LoadBestPricesFromSolutionFile(args[1]);
            var relativeErrors = results.Select((result, index) => ComputeRelativeError(bestPrices[index], result.BestPrice)).ToList();
            Console.WriteLine($"Average relative error is {relativeErrors.Average()}.");
            Console.WriteLine($"Max relative error is {relativeErrors.Max()}.");

            Console.ReadLine();
        }
        private void RunGA(){
            _teams = LoadTeams();
            _winners = _teams.FindAll(l => l.Winner == true);
            _losers = _teams.FindAll(l => l.Winner == false);

            const double crossoverProbability = 0.85;
            const double mutationProbability = 0.15;
            const int elitismPercentage = 5;

            var population = new Population(1000, 72, true, false, ParentSelectionMethod.TournamentSelection);

            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.DoublePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            ga.OnGenerationComplete += ga_OnGenerationComplete;

            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            ga.Run(TerminateAlgorithm);

        }
    public DemoPlayerInputStrategy()
    {
        var population = new Population (6, 6, new DemoPlayerChromosome ());
        var fitness = new DemoPlayerFitness ();
        var selection = new EliteSelection ();
        var crossover = new OnePointCrossover (0);
        var mutation = new UniformMutation (true);

        m_ga = new GeneticAlgorithm (
            population,
            fitness,
            selection,
            crossover,
            mutation);

        m_ga.MutationProbability = 0.5f;
        m_ga.GenerationRan += (sender, e) => {
            m_bestChromossome = m_ga.BestChromosome as DemoPlayerChromosome;

            if(m_bestChromossome.AvoidAliensProjectilesProbability > 0.9f) {
                HorizontalDirection = 1f;
            }
        };
        m_ga.Start ();

        SHThread.PingPong (.01f, 0, 1, (t) => {
            m_ga.Termination = new GenerationNumberTermination (m_ga.GenerationsNumber + 1);
            m_ga.Resume();

            return true;
        });
    }
Example #5
0
        static void MainX()
        {
            functions= WeightedMetric.KnownFunctions.ToList();

            maps = mapIndices
                .Select(z => Problems.LoadProblems()[z.Item1].ToMap(z.Item2))
                .ToArray();
            baseline = maps.Select(z => Run(z, WeightedMetric.Test)).ToArray();

            var ga = new GeneticAlgorithm<ArrayChromosome<double>>(
                () => new ArrayChromosome<double>(functions.Count)
                , rnd);

            Solutions.AppearenceCount.MinimalPoolSize(ga, 10);
            Solutions.MutationOrigins.Random(ga,0.5);
            //Solutions.CrossFamilies.Random(ga, z => z * 0.5);
            Solutions.Selections.Threashold(ga, 8);

            ArrayGeneSolutions.Appearences.Double(ga);
            ArrayGeneSolutions.Mutators.Double(ga,0.1,0.1,0.5);
               // ArrayGeneSolutions.Crossover.Mix(ga);

            ga.Evaluate = chromosome =>
                {
                    chromosome.Value = Run(chromosome);
                };

            ConsoleGui.Run(ga, 1, Print);
        }
Example #6
0
        static void Algorithm()
        {
            var ga = new GeneticAlgorithm<ArrayChromosome<bool>>(()=>new ArrayChromosome<bool>(Count));

            Solutions.AppearenceCount.MinimalPoolSize(ga, 100);
            Solutions.MutationOrigins.Random(ga, 0.5);
            Solutions.CrossFamilies.Random(ga, z => z * 0.5);
            Solutions.Selections.Threashold(ga, 80);

            ArrayGeneSolutions.Appearences.Bool(ga);
            ArrayGeneSolutions.Mutators.Bool(ga);
            ArrayGeneSolutions.Crossover.Mix(ga);

            ga.Evaluate = chromosome =>
                {
                    chromosome.Value = 1 / (1 + Enumerable.Range(0, Count).Where(z => chromosome.Code[z]).Sum(z => Weights[z]));
                };

            while (true)
            {
                var watch = new Stopwatch();
                watch.Start();
                while (watch.ElapsedMilliseconds < 200)
                {
                    ga.MakeIteration();
                    averageValuations.Enqueue(ga.Pool.Average(z=>z.Value));
                    maxValuations.Enqueue(ga.Pool.Max(z=>z.Value));
                    ages.Enqueue(ga.Pool.Average(z=>z.Age));

                }
                watch.Stop();
                form.BeginInvoke(new Action(UpdateCharts));
            }
        }
Example #7
0
	public void Start()
	{
		//Debug.Log("Experiment n: " + _experimentsIdx);
		
		_fitnessCache = new Dictionary<AngryBirdsGen, float>();

		// Generate a population of feaseble levels evaluated by an inteligent agent
		_geneticAlgorithm = new GeneticAlgorithm<AngryBirdsGen>(_crossoverRate, _mutationRate, _populationSize, _generationSize, _elitism);
		_geneticAlgorithm.InitGenome = new GeneticAlgorithm<AngryBirdsGen>.GAInitGenome(InitAngryBirdsGenome);
		_geneticAlgorithm.Mutation = new GeneticAlgorithm<AngryBirdsGen>.GAMutation(Mutate);
		_geneticAlgorithm.Crossover = new GeneticAlgorithm<AngryBirdsGen>.GACrossover(Crossover);
		_geneticAlgorithm.FitnessFunction = new GeneticAlgorithm<AngryBirdsGen>.GAFitnessFunction(EvaluateUsingAI);	
		_geneticAlgorithm.StartEvolution();

		_isRankingGenome = false;
		_generationIdx = 0;
		_genomeIdx = 0;

		// Set time scale to acelerate evolution
		Time.timeScale = 100f;
		 
		// Totally zoom out
		GameWorld.Instance._camera.SetCameraWidth(Mathf.Infinity);
		
		// Remove all objects from level before start
		GameWorld.Instance.ClearWorld();
	}
Example #8
0
 void Start()
 {
     doors = GameObject.Find ("Gates");
     ga = GetComponent<GeneticAlgorithm>();
     ga.shufflePopulation ();
     spawnWave(1);
 }
    public override void Select(Population population, SelectionBuffer selection, GeneticAlgorithm.NextStepDelegate callback)
    {
        int size = 0;

        // TODO: Implement settings for how to truncate.
        float cutoff = 0;
        switch (truncationMode) {
        case TruncationMode.AboveMiddle:
            cutoff = population.MinFitness + (population.MaxFitness - population.MinFitness)/2;
            break;
        case TruncationMode.AboveMean:
            cutoff = population.MeanFitness;
            break;
        case TruncationMode.AboveMedian:
            cutoff = population.MedianFitness;
            break;
        }

        for (int i = 0; i < population.Size; i++) {
            if (population[i].Fitness > cutoff) {
                selection[size].CloneFrom(population[i].Genome);
                size++;
            }
        }

        selection.Size = size;
        callback();
    }
Example #10
0
        public static void FindBestStrategyForGame(GameConfig gameConfig)
        {
            var initialDescription = new PickByPriorityDescription(new CardAcceptanceDescription[]
            {
                new CardAcceptanceDescription( Cards.Province, new MatchDescription[] { new MatchDescription( null, CountSource.None, Comparison.None, 0)}),
                new CardAcceptanceDescription( Cards.Gold, new MatchDescription[] { new MatchDescription( null, CountSource.None, Comparison.None, 0)}),
                new CardAcceptanceDescription( Cards.Silver, new MatchDescription[] { new MatchDescription( null, CountSource.None, Comparison.None, 0)})
            });

            Random random = new Random();

            Card[] supplyCards = gameConfig.GetSupplyPiles(2, random).Select(pile => pile.ProtoTypeCard).ToArray();

            var initialPopulation = Enumerable.Range(0, 10).Select(index => initialDescription).ToArray();
            var algorithm = new GeneticAlgorithm<PickByPriorityDescription, MutatePickByPriorityDescription, CompareStrategies>(
                initialPopulation,
                new MutatePickByPriorityDescription(random, supplyCards),
                new CompareStrategies(),
                new Random());

            for (int i = 0; i < 1000; ++i)
            {
                System.Console.WriteLine("Generation {0}", i);
                System.Console.WriteLine("==============", i);
                for (int j = 0; j < 10; ++j)
                {
                    algorithm.currentMembers[j].Write(System.Console.Out);
                    System.Console.WriteLine();
                }

                algorithm.RunOneGeneration();

                System.Console.WriteLine();
            }
        }
Example #11
0
    public override void FitnessFunction(Population population, GeneticAlgorithm.NextStepDelegate callback)
    {
        for (int i = 0; i < population.Size; i++) {
            PhenomeDescription pd = population[i];
            pd.Fitness = CalculateFitness(pd.Genome as BaseGenomeBinary);
        }

        CalculateMinMaxTotal(population);
        callback();
    }
 public FuzzyGeneticsRunParameters(GeneticAlgorithm algorithm, GeneticInstanceParameters algorithmInstanceParameters,
     GeneticRunParameters algorithmRunParameters, int numberToAverageScoreOver, int waitSinceLastImprovement, bool verbose)
 {
     this.algorithm = algorithm;
     this.algorithmInstanceParameters = algorithmInstanceParameters;
     this.algorithmRunParameters = algorithmRunParameters;
     this.numberToAverageScoreOver = numberToAverageScoreOver;
     this.waitSinceLastImprovement = waitSinceLastImprovement;
     this.verbose = verbose;
 }
 public RandomRestartRunParameters(GeneticAlgorithm algorithm, GeneticInstanceParameters algorithmInstanceParameters,
     GeneticRunParameters algorithmRunParameters, int promilleGoalDecreasePerRound, int numRepeatsBeforeRestart, bool verbose)
 {
     this.algorithm = algorithm;
     this.algorithmInstanceParameters = algorithmInstanceParameters;
     this.algorithmRunParameters = algorithmRunParameters;
     this.promilleGoalDecreasePerRound = promilleGoalDecreasePerRound;
     this.numRepeatsBeforeRestart = numRepeatsBeforeRestart;
     this.verbose = verbose;
 }
Example #14
0
    public virtual void FitnessFunctionSimple(Population population, GeneticAlgorithm.NextStepDelegate callback)
    {
        for (int i = 0; i < population.Size; i++) {
            PhenomeDescription pd = population[i];
            pd.Fitness = CalculateFitness(pd.Genome);
        }

        CalculateMinMaxTotal(population);
        callback();
    }
    // Use this for initialization
    void Start ()
    {
        mapInstances = FindObjectsOfType<Map>().ToList();
        if (!waveManager)
            waveManager = FindObjectOfType<WaveManager>();
        waveManager.OnWaveFinished += OnWaveFinished;
        waveManager.OnWaveStart += OnWaveStart; 
        ga = GetComponent<GeneticAlgorithm>();

        state = SceneState.Idle;
    }
Example #16
0
 // Use this for initialization
 void Start()
 {
     locker = GetComponentInParent<LockGates>();
     locked = true;
     anim = GetComponent<Animation>();
     player = GameObject.Find ("Warrior");
     roomspawner = GameObject.Find("Room Spawner").GetComponent<RoomSpawner>();
     enemies = GameObject.Find ("Spawner").GetComponent<SpawnEnemies>();
     exp = GameObject.Find ("Warrior").GetComponent<Experience>();
     ga = GameObject.Find ("Spawner").GetComponent<GeneticAlgorithm>();
     enemyspawner = GameObject.Find ("Spawner").GetComponent<SpawnEnemies>();
 }
Example #17
0
 public Status(GeneticAlgorithm ga)
 {
     ga.ReportStatus += OnReportStatus;
     StopCommand = new SimpleCommand(x => ga.Stop());
     AvgFitness = new BlockingCollection<DataPoint>();
     BestChromosome = new BlockingCollection<DataPoint>();
     Selection = new BlockingCollection<DataPoint>();
     Crossover = new BlockingCollection<DataPoint>();
     Mutation = new BlockingCollection<DataPoint>();
     Repair = new BlockingCollection<DataPoint>();
     Transform = new BlockingCollection<DataPoint>();
     Evaluation = new BlockingCollection<DataPoint>();
 }
Example #18
0
 public BulldozerWindow(GeneticAlgorithm<TreeChromosome> alg, Metric[] metrics, int iterationShowRate)
 {
     InitializeComponent();
     TexFormulaParser.Initialize();
     _alg = alg;
     _metrics = metrics;
     _iterationShowRate = iterationShowRate;
     _dispatcher = new GaDispatcher(alg);
     _manualStop = false;
     _alg.IterationCallBack += AlgIterationCallBack;
     FillPoolPanel();
     FillOptionalPanel();
 }
Example #19
0
    public override void Mate(SelectionBuffer selected, Population newPopulation, GeneticAlgorithm.NextStepDelegate callback)
    {
        // The new population is populated with 2 children each iteration.
        for (int i = 0; i < newPopulation.Size; i+=2) {
            BaseGenome mom = selected[Random.Range(0, selected.Size)]; // TODO: mom and dad can be the same..
            BaseGenome dad = selected[Random.Range(0, selected.Size)];

            int point = Random.Range(0, mom.Length);
            newPopulation[i].Genome.OnePointCrossover(mom, dad, point);
            newPopulation[i+1].Genome.OnePointCrossover(mom, dad, point);
        }
        callback();
    }
Example #20
0
    public override void Mutate(Population population, GeneticAlgorithm.NextStepDelegate callback)
    {
        for (int i = 0; i < population.Size; i++) {
            if (Random.value > mutationProbability)
                continue;

            BaseGenome genome = population[i].Genome;
            int nrMutations = Random.Range(0, (int)Mathf.Round(bitMutationFraction * genome.Length));
            for (int j = 0; j < nrMutations; j++) {
                genome.Modify(Random.Range(0, genome.Length));
            }
        }
        callback();
    }
Example #21
0
	private void Awake ()
	{
		var population = new Population (m_populationSize, m_populationSize, new CheckersChromosome (m_movesAhead, m_boardSize));
		Fitness = new CheckersFitness (new CheckersBoard (m_boardSize));
		GA = new GeneticAlgorithm (
			population, 
			Fitness, 
			new EliteSelection (),
			new UniformCrossover (),
			new UniformMutation ());
		
		GA.TaskExecutor = new SmartThreadPoolTaskExecutor();
		GA.TaskExecutor.Timeout = System.TimeSpan.FromSeconds (1);
	}
Example #22
0
    // This operator adds a unit Gaussian distributed random value to the chosen gene. If it falls outside of the user-specified lower or upper bounds for that gene,the new gene value is clipped. This mutation operator can only be used for integer and float genes.
    public override void Mutate(Population population, GeneticAlgorithm.NextStepDelegate callback)
    {
        for (int i = 0; i < population.Size; i++) {
            if (Random.value > mutationProbability)
                continue;

            GenomeFloatString genome = population[i].Genome as GenomeFloatString;
            float[] floats = genome.GetArray();
            int nrMutations = Random.Range(0, (int)Mathf.Round(bitMutationFraction * genome.Length));
            for (int j = 0; j < nrMutations; j++) {
                floats[j] += Random.Range(-0.1f, 0.1f);
            }
        }
        callback();
    }
 // Genetic Algorithm maxA testing method
 public static void main( String[] args )
 {
     // Initializing the population (we chose 500 genes for the population,
     // but you can play with the population size to try different approaches)
     GeneticAlgorithm population = new GeneticAlgorithm(POPULATION_SIZE);
     int generationCount = 0;
     // For the sake of this sample, evolution goes on forever.
     // If you wish the evolution to halt (for instance, after a number of
     //   generations is reached or the maximum fitness has been achieved),
     //   this is the place to make any such checks
     while(true){
         // --- evaluate current generation:
         population.evaluateGeneration();
         // --- print results here:
         // we choose to print the average fitness,
         // as well as the maximum and minimum fitness
         // as part of our progress monitoring
         float avgFitness=0f;
         float minFitness=float.PositiveInfinity;
         float maxFitness=float.NegativeInfinity;
         string bestIndividual="";
         string worstIndividual="";
         for(int i = 0; i < population.size(); i++){
             float currFitness = population.getGene(i).getFitness();
             avgFitness += currFitness;
             if(currFitness < minFitness){
                 minFitness = currFitness;
                 worstIndividual = population.getGene(i).getPhenotype();
             }
             if(currFitness > maxFitness){
                 maxFitness = currFitness;
                 bestIndividual = population.getGene(i).getPhenotype();
             }
         }
         if(population.size()>0){ avgFitness = avgFitness/population.size(); }
         string output = "Generation: " + generationCount;
         output += "\t AvgFitness: " + avgFitness;
         output += "\t MinFitness: " + minFitness + " (" + worstIndividual +")";
         output += "\t MaxFitness: " + maxFitness + " (" + bestIndividual +")";
         Debug.Log(output);
         // produce next generation:
         population.produceNextGeneration();
         generationCount++;
     }
 }
Example #24
0
    public override void Select(Population population, SelectionBuffer selection, GeneticAlgorithm.NextStepDelegate callback)
    {
        int size = 0;
        DebugAux.Assert(population.MaxFitness != 0, "[RouletteWheelSA] Can't have a MaxFitness of zero!");

        // The algorithm states that we should pick one at random for consideration with probability 1/N.
        int nrConsiderations = Mathf.RoundToInt(population.Size * Settings.SelectionProportion);
        for (int i = 0; i < nrConsiderations; i++) {
            int index = Random.Range(0, population.Size);
            float probability = population[index].Fitness / population.MaxFitness;
            if (Random.value <= probability) {
                selection[size].CloneFrom(population[index].Genome);
                size++;
            }
        }

        selection.Size = size;
        callback();
    }
 public GeneticAlgorithmTests()
 {
     Algorithm = new GeneticAlgorithm(_graphFactory.ProvideValid(), 
         _problemProvider.ProvideSubstitute(), 
         _operatorsProvider.ProvideSubstitute(), 
         _settingsProvider.ProvideValid());
     _geneticAlgorithmThatAlwaysCrossoversAndMutates = new GeneticAlgorithm(_graphFactory.ProvideValid(),
         _problemProvider.ProvideSubstitute(),
         _operatorsProvider.ProvideSubstitute(),
         new GeneticAlgorithmSettings(generationsToCome: 1, crossoverProbability: 1d, mutationProbability: 1d));
     _geneticAlgorithmThatHasLotsOfGenerations = new GeneticAlgorithm(_graphFactory.ProvideValid(),
         _problemProvider.ProvideSubstitute(),
         _operatorsProvider.ProvideSubstitute(),
         new GeneticAlgorithmSettings(generationsToCome: 20, initialPopulationSize: 4));
     _geneticAlgorithmThatAlwaysCrossoversAndMutatesAndPerformsElitism = new GeneticAlgorithm(_graphFactory.ProvideValid(),
         _problemProvider.ProvideSubstitute(),
         _operatorsProvider.ProvideSubstitute(),
         new GeneticAlgorithmSettings(generationsToCome: 1, crossoverProbability: 1d, mutationProbability: 1d, withElitistSelection: true));
 }
Example #26
0
    // Use this for initialization
    void Start()
    {
        ga = new GeneticAlgorithm();
        int totalWeights = 5 * 8 + 8 * 2 + 8 + 2;
        ga.GeneratePopulation(15, totalWeights);
        currentFitness = 0.0f;
        bestFitness = 0.0f;

        net = new NeuralNetwork(1, 5, 8, 2);
        Genome genome = ga.GetNextGenome();
        net.FromGenome(genome, 5, 8, 2);

        testAgent = gameObject.GetComponent<Agent>();
        testAgent.Attach(net);

        hit = gameObject.GetComponent<CheckpointHit>();
        checkpointsNum = hit.checkpoints;
        defaultpos = transform.position;
        defaultrot = transform.rotation;
    }
Example #27
0
        public void TestGAF()
        {


            var population = new Population();

            int popSize = 100;
            for (int i = 0; i < popSize; i++)
            {
                var tmpStock = new int[stocks.Length];
                var tmpItemsCount = new int[itemsCount.Length];
                stocks.CopyTo(tmpStock, 0);
                itemsLength.CopyTo(tmpItemsCount, 0);

                Debug.WriteLine("************************************");
                Debug.WriteLine("Create new Chromosome");
                var chromosome = new Chromosome();
                for (int k = 0; k < stocks.Length; k++)
                {

                    Gene gene;
                    if (Rnd(k, ref tmpItemsCount, out gene))
                        chromosome.Genes.Add(gene);
                }
                chromosome.Genes.ShuffleFast();
                population.Solutions.Add(chromosome);


            }

            var elite = new Elite(10);
            var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.SinglePoint };
            var mutate = new SwapMutate(0.02);
            var ga = new GeneticAlgorithm(population, CalculateFitness);
            ga.OnGenerationComplete += Ga_OnGenerationComplete;
            ga.OnRunComplete += Ga_OnRunComplete;
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);
            ga.Run(50);
        }
  public override void Main() {
    var ga = new GeneticAlgorithm {
      MaximumGenerations = { Value = 50 },
      PopulationSize = { Value = 10 },
      Problem = new TravelingSalesmanProblem()
    };

    var experiment = new Experiment();
    for (int i = 0; i < 5; i++) {
      experiment.Optimizers.Add(new BatchRun() { Optimizer = (IOptimizer)ga.Clone(), Repetitions = 10 });
      ga.PopulationSize.Value *= 2;
    }

    experiment.ExecutionStateChanged += OnExecutionStateChanged;
    experiment.Start();
    mutex.WaitOne();

    vars.experiment = experiment;
    MainFormManager.MainForm.ShowContent(experiment);
    var viewHost = (ViewHost)MainFormManager.MainForm.ShowContent(experiment.Runs, typeof(RunCollectionBubbleChartView));
    var bubbleChart = (UserControl)(viewHost.ActiveView);
    bubbleChart.Controls.OfType<ComboBox>().Single(x => x.Name == "yAxisComboBox").SelectedItem = "BestQuality";
    bubbleChart.Controls.OfType<ComboBox>().Single(x => x.Name == "xAxisComboBox").SelectedItem = "PopulationSize";
  }
Example #29
0
 protected virtual void AssertCrossover(GeneticAlgorithm ga)
 {
     ga.Crossover.Should().BeOfType <OrderedCrossover>();
 }
Example #30
0
    static void Main(string[] args)
    {
        QAPAlgorithm test = null;

        string command = "";

        while (command != "exit")
        {
            command = Console.ReadLine();
            switch (command)
            {
            case "gen":
                //Console.WriteLine("nOfGenerations: ");
                //int nOfGenerations = Int32.Parse(Console.ReadLine());
                //Console.WriteLine("p_crossover: ");
                //double p_crossover = Double.Parse(Console.ReadLine());
                //Console.WriteLine("p_mutation: ");
                //double p_mutation = Double.Parse(Console.ReadLine());
                //Console.WriteLine("tourn_size: ");
                //int tourn_size = Int32.Parse(Console.ReadLine());
                //Console.WriteLine("pop_size: ");
                //int pop_size = Int32.Parse(Console.ReadLine());
                //Console.WriteLine("test_case: ");
                //int gen_test_case = Int32.Parse(Console.ReadLine());

                //base
                test = new GeneticAlgorithm(100, 100, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                //test selection
                test = new GeneticAlgorithm(100, 100, 0.7, 0.01, SelectionMethod.Roulette, 1, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.01, SelectionMethod.Tournament, 1, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.01, SelectionMethod.Tournament, 2, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.01, SelectionMethod.Tournament, 10, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.01, SelectionMethod.Tournament, 25, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.01, SelectionMethod.Tournament, 100, $"input{12}.txt"); test.Run();
                //test mutation
                test = new GeneticAlgorithm(100, 100, 0.7, 0.00, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.02, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.05, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.10, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.20, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.50, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 1.00, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                //test crossover
                test = new GeneticAlgorithm(100, 100, 0.0, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.2, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.4, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.5, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.6, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.8, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 1.0, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                //test pop-size
                test = new GeneticAlgorithm(100, 10, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 20, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 50, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 200, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 500, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                //test gen-count
                test = new GeneticAlgorithm(10, 100, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(20, 100, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(50, 100, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(100, 100, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(200, 100, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                test = new GeneticAlgorithm(500, 100, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                //test both
                test = new GeneticAlgorithm(500, 500, 0.7, 0.01, SelectionMethod.Tournament, 5, $"input{12}.txt"); test.Run();
                Console.WriteLine("done!");

                break;

            case "grd":
                Console.WriteLine("starting_point: ");
                int starting_point = Int32.Parse(Console.ReadLine());
                Console.WriteLine("test_case: ");
                int grd_test_case = Int32.Parse(Console.ReadLine());

                test = new GreedyAlgorithm(starting_point, $"input{grd_test_case}.txt");

                break;

            case "rnd":
                Console.WriteLine("best_of: ");
                int best_of = Int32.Parse(Console.ReadLine());
                Console.WriteLine("test_case: ");
                int rnd_test_case = Int32.Parse(Console.ReadLine());

                test = new RandomAlgorithm(best_of, $"input{rnd_test_case}.txt");

                break;

            default:
                Console.WriteLine("wut");
                break;
            }

            if (test != null)
            {
                test.Input.ReadFile();
                Console.WriteLine(test.Evaluate(test.Run()));
            }
        }
    }
Example #31
0
        internal void Run(AreaManager areaManager, Population conv, Population inno, Population obj)
        {
            if (running)
            {
                return;
            }

            cells = originalMap.SpawnCells;


            Chromosome chrom = ChromosomeUtils.ChromosomeFromMap(originalMap);

            string binaryString = chrom.ToBinaryString();

            convergenceFitness = new ConvergenceFitness(cells, binaryString);
            guidelineFitness   = new Guideline(cells, areaManager, MaxMonsters, MaxItens, HordesPercentage)
            {
                MaxItemsLever      = LeverMaxItem,
                MaxMonstersLever   = LeverMaxMonster,
                AmountHordesLever  = LeverAmountHordes,
                DangerLever        = LeverDanger,
                AccessibilityLever = LeverAccessibility
            };

            double total = GuidelinePercentage + UserPercentage + InnovationPercentage;

            guidelineLevel   = GuidelinePercentage / total;
            ConvergenceLevel = UserPercentage / total;
            innovationLevel  = InnovationPercentage / total;

            //we can create an empty population as we will be creating the
            //initial solutions manually.
            var population = new Population(InitialPopulation, cells.Count * ChromosomeUtils.NUMBER_GENES, true, true, ParentSelectionMethod.StochasticUniversalSampling);

            population.Solutions.Clear();

            population.Solutions.AddRange(obj.GetTop(10));
            population.Solutions.AddRange(inno.GetTop(10));
            population.Solutions.AddRange(conv.GetTop(10));

            //create the elite operator
            var elite = new Elite(ElitismPercentage);

            //create the crossover operator
            var crossover = new CrossoverIndex(CrossOverPercentage, ChromosomeUtils.NUMBER_GENES, true, GAF.Operators.CrossoverType.DoublePoint, ReplacementMethod.GenerationalReplacement);

            //create the mutation operator
            var mutate = new BinaryMutate(MutationPercentage);
            //create the GA
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            //ga.Operators.Add(mutate);

            ga.OnRunComplete += OnRunComplete;

            //run the GA
            running = true;
            ga.Run(TerminateFunction);
        }
Example #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AlgorithmOptimumFinder"/> class
        /// </summary>
        /// <param name="start">Algorithm start date</param>
        /// <param name="end">Algorithm end date</param>
        /// <param name="fitScore">Argument of <see cref="FitnessScore"/> type. Fintess function to rank the backtest results</param>
        /// <param name="filterEnabled">Indicates whether to apply fitness filter to backtest results</param>
        public AlgorithmOptimumFinder(DateTime start, DateTime end, FitnessScore fitScore, bool filterEnabled)
        {
            // Assign Dates and Criteria to sort the results
            StartDate    = start;
            EndDate      = end;
            FitnessScore = fitScore;

            // Common properties
            var selection = new RouletteWheelSelection();

            // Properties specific to optimization modes
            IFitness       fitness;
            PopulationBase population;
            ITaskExecutor  executor;
            ITermination   termination;

            // Task execution mode
            switch (Shared.Config.TaskExecutionMode)
            {
            // Enable fitness filtering while searching for optimum parameters
            case TaskExecutionMode.Linear:
                executor = new LinearTaskExecutor();
                fitness  = new OptimizerFitness(StartDate, EndDate, fitScore, filterEnabled);
                break;

            case TaskExecutionMode.Parallel:
                executor = new ParallelTaskExecutor();
                fitness  = new OptimizerFitness(StartDate, EndDate, fitScore, filterEnabled);
                break;

            case TaskExecutionMode.Azure:
                executor = new ParallelTaskExecutor();
                fitness  = new AzureFitness(StartDate, EndDate, fitScore, filterEnabled);
                break;

            default:
                throw new Exception("Executor initialization failed");
            }

            // Optimization mode
            switch (Shared.Config.OptimizationMode)
            {
            case OptimizationMode.BruteForce:
            {
                // Create cartesian population
                population  = new PopulationCartesian(Shared.Config.GeneConfigArray);
                termination = new GenerationNumberTermination(1);

                break;
            }

            case OptimizationMode.Genetic:
            {
                // Create random population
                population = new PopulationRandom(Shared.Config.GeneConfigArray, Shared.Config.PopulationInitialSize)
                {
                    GenerationMaxSize = Shared.Config.GenerationMaxSize
                };

                // Logical terminaton
                var localTerm = new LogicalOrTermination();

                localTerm.AddTermination(new FruitlessGenerationsTermination(3));

                if (Shared.Config.Generations.HasValue)
                {
                    localTerm.AddTermination(new GenerationNumberTermination(Shared.Config.Generations.Value));
                }

                if (Shared.Config.StagnationGenerations.HasValue)
                {
                    localTerm.AddTermination(new FitnessStagnationTermination(Shared.Config.StagnationGenerations.Value));
                }

                termination = localTerm;
                break;
            }

            default:
                throw new Exception("Optimization mode specific objects were not initialized");
            }

            // Create GA itself
            GenAlgorithm = new GeneticAlgorithm(population, fitness, executor)
            {
                // Reference types
                Selection   = selection,
                Termination = termination,

                // Values types
                CrossoverParentsNumber  = Shared.Config.CrossoverParentsNumber,
                CrossoverMixProbability = Shared.Config.CrossoverMixProbability,
                MutationProbability     = Shared.Config.MutationProbability
            };
        }
Example #33
0
        static void Main(string[] args)
        {
//            var chromosome = new E2Chromosome(5, 5);
//            Console.WriteLine(chromosome.ToString());
//
//            int n = 0;
//            foreach (var cutTile in E2Chromosome.CutTiles(chromosome))
//            {
//                Console.Write(cutTile + " ");
//                if ( ++n % 5 == 0)Console.WriteLine();
//            }
//
//            Console.ReadLine();

            // Setup problem
            E2Chromosome.Width     = 5;
            E2Chromosome.Height    = 5;
            E2Chromosome.TileCount = E2Chromosome.Width * E2Chromosome.Height;
            E2Chromosome.Tiles     = new string[]
            {
                "ABDC", "DEBF", "BGGE", "GCFF", "FEED",
                "CCBF", "BFCC", "CEGG", "GFAH", "ADDC",
                "FFAC", "ACHE", "HGBC", "BHAF", "ACHG",
                "ECFC", "FEDB", "DCGB", "GFCA", "CGFD",
                "ECBE", "BBGC", "GBCH", "CAHD", "HDCE"
            }.Select(t => new Tile(t));

            // Create chromosome and fitness
            var chromosome = new E2Chromosome();
            var fitness    = new E2Fitness();

            // This operators are classic genetic algorithm operators that lead to a good solution on TSP,
            // but you can try others combinations and see what result you get.
            var crossover  = new GeneticSharp.Domain.Crossovers.OnePointCrossover();
            var mutation   = new GeneticSharp.Domain.Mutations.PartialShuffleMutation();
            var selection  = new GeneticSharp.Domain.Selections.RouletteWheelSelection();
            var population = new GeneticSharp.Domain.Populations.Population(5000, 10000, chromosome);

            ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);
            ga.MutationProbability = 0.1f;
            ga.Termination         = new GeneticSharp.Domain.Terminations.FitnessThresholdTermination(1.0);

            // The fitness evaluation of whole population will be running on parallel.
            ga.TaskExecutor = new ParallelTaskExecutor
            {
                MinThreads = 100,
                MaxThreads = 200
            };

            // Every time a generation ends, we log the best solution.
            int      bestMatches = 0;
            DateTime startTime   = DateTime.Now;

            ga.GenerationRan += delegate
            {
                var best    = ((E2Chromosome)ga.BestChromosome);
                var Matches = best.Matches;
                var Fitness = best.FitnessValue;

                if (Matches > bestMatches || ga.GenerationsNumber % 250 == 0)
                {
                    Console.WriteLine(
                        $"{DateTime.Now.Subtract(startTime).TotalSeconds}s Generation: {ga.GenerationsNumber} - Matches: {Matches} - Fitness: {Fitness}");

                    if (Matches > bestMatches)
                    {
                        Console.WriteLine(((E2Chromosome)ga.BestChromosome).ToStringIncludingTileMatches(true));
                    }

                    bestMatches = Matches;
                }
            };

            // Starts the genetic algorithm in a separate thread.
            gaThread = new Thread(() => ga.Start());
            gaThread.Start();


            Console.ReadLine();


            // When the script is destroyed we stop the genetic algorithm and abort its thread too.
            ga.Stop();
            gaThread.Abort();
        }
Example #34
0
 void Start()
 {
     bestDNA = FindObjectOfType <GeneticAlgorithm>();
 }
Example #35
0
 /// <summary>
 /// Initializes the state of this class.
 /// </summary>
 /// <param name="algorithm">The <see cref="GenFx.GeneticAlgorithm"/> associated with this context.</param>
 public ExecutionContext(GeneticAlgorithm algorithm)
 {
     this.GeneticAlgorithm = algorithm;
 }
Example #36
0
 public CustomGenome(GeneticAlgorithm parent, int numberOfValues) : base(parent)
 {
     this.ga      = parent;
     this.alleles = new int[numberOfValues];
 }
Example #37
0
        static void Main(string[] args)
        {
            knapsackItems = new List <Bag.Item>();
            knapsackItems.Add(new Bag.Item()
            {
                Name = "a", Weight = 9, Value = 150
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "b", Weight = 153, Value = 200
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "c", Weight = 13, Value = 35
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "d", Weight = 50, Value = 160
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "e", Weight = 15, Value = 60
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "f", Weight = 68, Value = 45
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "g", Weight = 27, Value = 60
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "h", Weight = 39, Value = 40
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "i", Weight = 23, Value = 30
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "j", Weight = 52, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "k", Weight = 11, Value = 70
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "l", Weight = 32, Value = 30
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "m", Weight = 24, Value = 15
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "n", Weight = 48, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "o", Weight = 73, Value = 40
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "p", Weight = 42, Value = 70
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "q", Weight = 22, Value = 80
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "r", Weight = 7, Value = 20
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "s", Weight = 18, Value = 12
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "t", Weight = 4, Value = 50
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "u", Weight = 30, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "v", Weight = 43, Value = 75
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "v", Weight = 43, Value = 75
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "v", Weight = 43, Value = 75
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "v", Weight = 43, Value = 75
            });

            const double crossoverProbability = 0.65;
            const double mutationProbability  = 0.08;
            const int    elitismPercentage    = 5;

            // tao quan the
            var population = new Population(100, 22, false, false);

            // tao toan tu di truyen
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };
            var mutation = new BinaryMutate(mutationProbability, true);

            // tao GA
            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            ga.OnGenerationComplete += ga_OnGenerationComplete;

            // them tung toan tu vao GA
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            // chay GA
            ga.Run(TerminateAlgorithm);

            // lay do vat tot nhat
            var Bestchromosome = ga.Population.GetTop(1)[0];

            // decode chromosome
            Console.WriteLine("Maximum value of knapsack contains these Items : ");
            Bag BestBag = new Bag();

            for (int i = 0; i < Bestchromosome.Count; i++)
            {
                if (Bestchromosome.Genes[i].BinaryValue == 1)
                {
                    Console.WriteLine(knapsackItems[i].ToString());
                    BestBag.AddItem(knapsackItems[i]);
                }
            }
            Console.WriteLine(" Best knapsack information:\n Total Weight : {0}   Total Value : {1} Fitness : {2}", BestBag.TotalWeight, BestBag.TotalValue, Bestchromosome.Fitness);
            Console.ReadKey();
        }
        private AssignmentTwoResultList <GraphGenome> GeneticLocalSearch(INeighborhood <GraphGenome> neighborhood)
        {
            AssignmentTwoResultList <GraphGenome> results = new AssignmentTwoResultList <GraphGenome>("$GLS_{" + neighborhood.Name + "}$");

            GraphGenome graph = new GraphGenome(500);

            graph.CreateGraph("Graph500.txt");

            GraphGenome optimum = null;

            for (int i = 0; i < ExperimentAmount; ++i)
            {
                AssignmentTwoResults <GraphGenome> res = new AssignmentTwoResults <GraphGenome>();
                int population_size = 50;
                int data_size       = 500;

                LocalSearch <GraphGenome> local_search =
                    new LocalSearch <GraphGenome>(data_size,
                                                  neighborhood,
                                                  new GraphComparer <GraphGenome>(), main_random_source);

                LocalSearchProcreator <GraphGenome> lsp = new LocalSearchProcreator <GraphGenome>(
                    new UniformSymmetricCrossover <GraphGenome>(main_random_source),
                    local_search,
                    main_random_source,
                    res);

                GeneticAlgorithm <GraphGenome> ga = new GeneticAlgorithm <GraphGenome>(
                    data_size,
                    lsp,
                    new DefaultSelector <GraphGenome>(
                        new GraphComparer <GraphGenome>()),
                    new LocalSearchPopulationGenerator <GraphGenome>(main_random_source, local_search),
                    new Goal(100, 0),
                    main_random_source,
                    "GLS");

                InnerResult ir = ga.start(population_size, OptimaAmount / (population_size / 2));
                // Eventueel nog een keer uitvoeren om tot 2500 optima te komen.
                while (res.Count < OptimaAmount)
                {
                    ir = ga.start(population_size, OptimaAmount / (population_size / 2));
                }

                // Als we er teveel hebben gekregen door de GLS run meerdere keren uit te voeren,
                // pak enkel hoeveel we nodig hebben.
                res = res.TakeFirstN(OptimaAmount);
                results.Add(res);

                if (optimum == null || res.BestResult.Optimum.Fitness < optimum.Fitness)
                {
                    optimum = new GraphGenome(res.BestResult.Optimum.Data, res.BestResult.Optimum.Fitness);
                }
            }



            // We maken iedere keer population_size / 2 optima.
            // We willen OptimaAmount optima. Dus we gaan OptimaAmount / (population_size / 2) generaties uitvoeren.

            //IteratedLocalSearch();

            optimum.ToImage(String.Format("results/GLS[{0}]-{1}.bmp", neighborhood.Name, optimum.Fitness), 3000, 3000);

            return(results);
        }
Example #39
0
 protected override bool PerformHasReached(GeneticAlgorithm geneticAlgorithm)
 {
     return(geneticAlgorithm.Population.CurrentGeneration.GenerationIndex >= _iterationThreshold);
 }
Example #40
0
        /**
         *  一次迭代计算
         * @param tree  板件列表(去掉了带孔的多边形内孔的点集)
         * @param binPolygon    底板
         * @param config    设置
         * @return
         */
        public Result launchWorkers(List <NestPath> tree, NestPath binPolygon, Config config)
        {
            launchcount++;
            if (GA == null)
            {
                List <NestPath> adam = new List <NestPath>();
                foreach (var nestPath in tree)
                {
                    var clone = new NestPath(nestPath);
                    adam.Add(clone);
                }
                foreach (NestPath nestPath in adam)
                {
                    nestPath.area = GeometryUtil.polygonArea(nestPath);
                }
                //按零件的面积由大到小排序
                adam.Sort((x, y) => x.area.CompareTo(y.area));
                //Collections.sort(adam);
                GA = new GeneticAlgorithm(adam, binPolygon, config);
            }

            Individual individual = null;

            for (int i = 0; i < GA.population.Count; i++)
            {
                if (GA.population[i].getFitness() < 0)
                {
                    individual = GA.population[i];
                    break;
                }
            }
            //        if(individual == null ){
            //            GA.generation();
            //            individual = GA.population.get(1);
            //        }
            if (launchcount > 1 && individual == null)
            {
                GA.generation();
                individual = GA.population[1];
            }

            // 以上为GA

            List <NestPath> placelist = individual.getPlacement();
            List <double>   rotations = individual.getRotation();

            List <int> ids = new List <int>();

            for (int i = 0; i < placelist.Count; i++)
            {
                ids.Add(placelist[i].getId());
                placelist[i].setRotation(rotations[i]);
            }
            List <NfpPair> nfpPairs = new List <NfpPair>();
            NfpKey         key      = null;

            /**
             * 如果在nfpCache里没找到nfpKey 则添加进nfpPairs
             */
            for (int i = 0; i < placelist.Count; i++)
            {
                NestPath part = placelist[i];
                //这个是零件和底板之间形成的nfp,所以inside这个参数为true
                key = new NfpKey(binPolygon.getId(), part.getId(), true, 0, part.getRotation());
                if (!nfpCache.ContainsKey(serialize.Serialize(key)))
                {
                    nfpPairs.Add(new NfpPair(binPolygon, part, key));
                }
                else
                {
                }

                //这个是零件之间相互形成的nfp,所以inside这个参数为false
                for (int j = 0; j < i; j++)
                {
                    NestPath placed = placelist[j];
                    NfpKey   keyed  = new NfpKey(placed.getId(), part.getId(), false, rotations[j], rotations[i]);
                    nfpPairs.Add(new NfpPair(placed, part, keyed));
                }
            }


            /**
             * 第一次nfpCache为空 ,nfpCache存的是nfpKey所对应的两个polygon所形成的Nfp( List<NestPath> )
             */
            List <ParallelData> generatedNfp = new List <ParallelData>();

            foreach (NfpPair nfpPair in nfpPairs)
            {
                ParallelData dataTemp = NfpUtil.nfpGenerator(nfpPair, config);
                generatedNfp.Add(dataTemp);
            }
            for (int i = 0; i < generatedNfp.Count; i++)
            {
                ParallelData Nfp = generatedNfp[i];
                //TODO remove gson & generate a new key algorithm
                String tkey = serialize.Serialize(Nfp.getKey()); //gson.toJson(Nfp.getKey());
                if (!nfpCache.ContainsKey(tkey))
                {
                    nfpCache.Add(tkey, Nfp.value);
                }
                else
                {
                }
            }

            PlacementWorker worker         = new PlacementWorker(binPolygon, config, nfpCache);
            List <NestPath> placeListSlice = new List <NestPath>();



            for (int i = 0; i < placelist.Count; i++)
            {
                placeListSlice.Add(new NestPath(placelist[i]));
            }
            List <List <NestPath> > data = new List <List <NestPath> >();

            data.Add(placeListSlice);
            List <Result> placements = new List <Result>();

            for (int i = 0; i < data.Count; i++)
            {
                Result result = worker.placePaths(data[i]);
                placements.Add(result);
            }
            if (placements.Count == 0)
            {
                return(null);
            }
            individual.fitness = placements[0].fitness;
            Result bestResult = placements[0];

            for (int i = 1; i < placements.Count; i++)
            {
                if (placements[i].fitness < bestResult.fitness)
                {
                    bestResult = placements[i];
                }
            }
            return(bestResult);
        }
 /// <inheritdoc/>
 public void Claim(GeneticAlgorithm ga)
 {
     foreach (IGenome genome  in  _genomes)
     {
         genome.GA = ga;
     }
 }
Example #42
0
        /// <summary>
        /// Example:
        ///
        /// http://diegogiacomelli.com.br/function-optimization-with-geneticsharp/
        /// </summary>
        static void Main(string[] args)
        {
            float maxWidth  = 998;
            float maxHeight = 680;

            var chromosome = new FloatingPointChromosome(
                new double[] { 0, 0, 0, 0, },
                new double[] { maxWidth, maxHeight, maxWidth, maxHeight },
                new int[] { 10, 10, 10, 10 },
                new int[] { 0, 0, 0, 0 });

            var population = new Population(50, 100, chromosome);

            var fitness = new FuncFitness((c) =>
            {
                var fc = c as FloatingPointChromosome;

                var values = fc.ToFloatingPoints();
                var x1     = values[0];
                var y1     = values[1];
                var x2     = values[2];
                var y2     = values[3];

                return(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)));
            });

            var selection   = new EliteSelection();
            var crossover   = new UniformCrossover(0.5f);
            var mutation    = new FlipBitMutation();
            var termination = new FitnessStagnationTermination(100);

            var ga = new GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation);

            ga.Termination = termination;

            Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance");

            var latestFitness = 0.0;

            ga.GenerationRan += (sender, e) =>
            {
                var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
                var bestFitness    = bestChromosome.Fitness.Value;

                if (bestFitness != latestFitness)
                {
                    latestFitness = bestFitness;
                    var phenotype = bestChromosome.ToFloatingPoints();

                    Console.WriteLine(
                        "Generation {0,2}: ({1},{2}),({3},{4}) = {5}",
                        ga.GenerationsNumber,
                        phenotype[0],
                        phenotype[1],
                        phenotype[2],
                        phenotype[3],
                        bestFitness
                        );
                }
            };

            ga.Start();

            Console.ReadKey();
        }
        private GeneticAlgorithm CreateGpSymbolicClassificationSample()
        {
            GeneticAlgorithm ga = new GeneticAlgorithm();

            #region Problem Configuration
            SymbolicClassificationSingleObjectiveProblem symbClassProblem = new SymbolicClassificationSingleObjectiveProblem();
            symbClassProblem.Name        = "Mammography Classification Problem";
            symbClassProblem.Description = "Mammography dataset imported from the UCI machine learning repository (http://archive.ics.uci.edu/ml/datasets/Mammographic+Mass)";
            UCIInstanceProvider provider = new UCIInstanceProvider();
            var instance  = provider.GetDataDescriptors().Where(x => x.Name.Equals("Mammography, M. Elter, 2007")).Single();
            var mammoData = (ClassificationProblemData)provider.LoadData(instance);
            mammoData.TargetVariableParameter.Value = mammoData.TargetVariableParameter.ValidValues
                                                      .First(v => v.Value == "Severity");
            mammoData.InputVariables.SetItemCheckedState(
                mammoData.InputVariables.Single(x => x.Value == "BI-RADS"), false);
            mammoData.InputVariables.SetItemCheckedState(
                mammoData.InputVariables.Single(x => x.Value == "Age"), true);
            mammoData.InputVariables.SetItemCheckedState(
                mammoData.InputVariables.Single(x => x.Value == "Shape"), true);
            mammoData.InputVariables.SetItemCheckedState(
                mammoData.InputVariables.Single(x => x.Value == "Margin"), true);
            mammoData.InputVariables.SetItemCheckedState(
                mammoData.InputVariables.Single(x => x.Value == "Density"), true);
            mammoData.InputVariables.SetItemCheckedState(
                mammoData.InputVariables.Single(x => x.Value == "Severity"), false);
            mammoData.TrainingPartition.Start = 0;
            mammoData.TrainingPartition.End   = 800;
            mammoData.TestPartition.Start     = 800;
            mammoData.TestPartition.End       = 961;
            mammoData.Name               = "Data imported from mammographic_masses.csv";
            mammoData.Description        = "Original dataset: http://archive.ics.uci.edu/ml/datasets/Mammographic+Mass, missing values have been replaced with median values.";
            symbClassProblem.ProblemData = mammoData;

            // configure grammar
            var grammar = new TypeCoherentExpressionGrammar();
            grammar.ConfigureAsDefaultClassificationGrammar();
            grammar.Symbols.OfType <VariableCondition>().Single().Enabled = false;
            foreach (var varSy in grammar.Symbols.OfType <VariableBase>())
            {
                varSy.VariableChangeProbability = 1.0;                                                     // for backwards compatibilty
            }
            var varSymbol = grammar.Symbols.OfType <Variable>().Single();
            varSymbol.WeightMu               = 1.0;
            varSymbol.WeightSigma            = 1.0;
            varSymbol.WeightManipulatorMu    = 0.0;
            varSymbol.WeightManipulatorSigma = 0.05;
            varSymbol.MultiplicativeWeightManipulatorSigma = 0.03;
            var constSymbol = grammar.Symbols.OfType <Constant>().Single();
            constSymbol.MaxValue         = 20;
            constSymbol.MinValue         = -20;
            constSymbol.ManipulatorMu    = 0.0;
            constSymbol.ManipulatorSigma = 1;
            constSymbol.MultiplicativeManipulatorSigma     = 0.03;
            symbClassProblem.SymbolicExpressionTreeGrammar = grammar;

            // configure remaining problem parameters
            symbClassProblem.BestKnownQuality.Value                    = 0.0;
            symbClassProblem.FitnessCalculationPartition.Start         = 0;
            symbClassProblem.FitnessCalculationPartition.End           = 400;
            symbClassProblem.ValidationPartition.Start                 = 400;
            symbClassProblem.ValidationPartition.End                   = 800;
            symbClassProblem.RelativeNumberOfEvaluatedSamples.Value    = 1;
            symbClassProblem.MaximumSymbolicExpressionTreeLength.Value = 100;
            symbClassProblem.MaximumSymbolicExpressionTreeDepth.Value  = 10;
            symbClassProblem.MaximumFunctionDefinitions.Value          = 0;
            symbClassProblem.MaximumFunctionArguments.Value            = 0;
            symbClassProblem.EvaluatorParameter.Value                  = new SymbolicClassificationSingleObjectiveMeanSquaredErrorEvaluator();
            #endregion
            #region Algorithm Configuration
            ga.Problem     = symbClassProblem;
            ga.Name        = "Genetic Programming - Symbolic Classification";
            ga.Description = "A standard genetic programming algorithm to solve a classification problem (Mammographic+Mass dataset)";
            SamplesUtils.ConfigureGeneticAlgorithmParameters <TournamentSelector, SubtreeCrossover, MultiSymbolicExpressionTreeManipulator>(
                ga, 1000, 1, 100, 0.15, 5
                );

            var mutator = (MultiSymbolicExpressionTreeManipulator)ga.Mutator;
            mutator.Operators.OfType <FullTreeShaker>().Single().ShakingFactor = 0.1;
            mutator.Operators.OfType <OnePointShaker>().Single().ShakingFactor = 1.0;

            ga.Analyzer.Operators.SetItemCheckedState(
                ga.Analyzer.Operators
                .OfType <SymbolicClassificationSingleObjectiveOverfittingAnalyzer>()
                .Single(), false);
            ga.Analyzer.Operators.SetItemCheckedState(
                ga.Analyzer.Operators
                .OfType <SymbolicDataAnalysisAlleleFrequencyAnalyzer>()
                .First(), false);
            #endregion
            return(ga);
        }
        public void RankSelectionOperator_Select()
        {
            GeneticAlgorithm      algorithm = GetAlgorithm();
            RankSelectionOperator op        = new RankSelectionOperator();

            op.Initialize(algorithm);
            SimplePopulation population = new SimplePopulation();

            population.Initialize(algorithm);
            MockEntity entity1 = new MockEntity();

            entity1.Initialize(algorithm);
            MockEntity entity2 = new MockEntity();

            entity2.Initialize(algorithm);
            MockEntity entity3 = new MockEntity();

            entity3.Initialize(algorithm);
            MockEntity entity4 = new MockEntity();

            entity4.Initialize(algorithm);
            entity1.ScaledFitnessValue = 0;
            entity2.ScaledFitnessValue = 50;
            entity3.ScaledFitnessValue = 23;
            entity4.ScaledFitnessValue = 25;
            population.Entities.Add(entity1);
            population.Entities.Add(entity2);
            population.Entities.Add(entity3);
            population.Entities.Add(entity4);

            TestRandomUtil randomUtil = new TestRandomUtil();

            RandomNumberService.Instance = randomUtil;

            randomUtil.Ratio = 0;
            IList <GeneticEntity> selectedEntities = op.SelectEntities(1, population).ToList();

            Assert.Same(entity1, selectedEntities[0]);

            randomUtil.Ratio = .099999;
            selectedEntities = op.SelectEntities(1, population);
            Assert.Same(entity1, selectedEntities[0]);

            randomUtil.Ratio = .1;
            selectedEntities = op.SelectEntities(1, population);
            Assert.Same(entity3, selectedEntities[0]);

            randomUtil.Ratio = .299999;
            selectedEntities = op.SelectEntities(1, population);
            Assert.Same(entity3, selectedEntities[0]);

            randomUtil.Ratio = .3;
            selectedEntities = op.SelectEntities(1, population);
            Assert.Same(entity4, selectedEntities[0]);

            randomUtil.Ratio = .599999;
            selectedEntities = op.SelectEntities(1, population);
            Assert.Same(entity4, selectedEntities[0]);

            randomUtil.Ratio = .6;
            selectedEntities = op.SelectEntities(1, population);
            Assert.Same(entity2, selectedEntities[0]);

            randomUtil.Ratio = 1;
            selectedEntities = op.SelectEntities(1, population);
            Assert.Same(entity2, selectedEntities[0]);
        }
Example #45
0
        /// <summary>
        /// Loads presetsProfile into service.
        /// </summary>
        /// <exception cref="T:System.InvalidOperationException">Thrown when an attempt to load presetsProfile twice is made.</exception>
        public void AddGeneticAlgorithm(GADefinition definition, Guid Key)
        {
            var chromosome = new FloatingPointChromosome(
                minValue: new double[] { 0, 0, 0, 0 },
                maxValue: new double[] { _maxWidth, _maxHeight, _maxWidth, _maxHeight },
                totalBits: new int[] { 20, 20, 20, 20 },
                fractionDigits: new int[] { 0, 0, 0, 0 }, geneValues: _geneValues);

            ICrossover gaCrossover = default;

            switch (definition.Crossover)
            {
            case Crossovers.Uniform:
                gaCrossover = new UniformCrossover(mixProbability: 0.5f);
                break;

            case Crossovers.OnePoint:
                gaCrossover = new OnePointCrossover(swapPointIndex: 40);
                break;

            case Crossovers.ThreeParent:
                gaCrossover = new ThreeParentCrossover();
                break;

            default:
                throw new ArgumentOutOfRangeException(paramName: nameof(definition.Crossover),
                                                      actualValue: definition.Crossover, message: "Crossover has wrong value");
            }

            ISelection gaSelection = default;

            switch (definition.Selection)
            {
            case Selections.Elite:
                gaSelection = new EliteSelection();
                break;

            case Selections.Roulette:
                gaSelection = new RouletteWheelSelection();
                break;

            case Selections.Tournament:
                gaSelection = new TournamentSelection(
                    size: decimal.ToInt32(d: decimal.Multiply(definition.Population, new decimal(0.2f))));
                break;

            case Selections.StohasticUniversalSampling:
                gaSelection = new StochasticUniversalSamplingSelection();
                break;

            default:
                throw new ArgumentOutOfRangeException(paramName: nameof(definition.Selection),
                                                      actualValue: definition.Selection, message: "Selection has wrong value");
            }

            var gaMutation = new UniformMutation(true);


            var gaPopulation = new Population(minSize: definition.Population,
                                              maxSize: definition.Population, adamChromosome: chromosome);

            var ga = new GeneticAlgorithm(population: gaPopulation,
                                          fitness: new EuclideanDistanceFitness(), selection: gaSelection,
                                          crossover: gaCrossover, mutation: gaMutation);

            ga.MutationProbability = (float)definition.Mutation;
            ga.GenerationRan      += GeneticAlgorithmOnGenerationRan;
            ga.Termination         =
                new FitnessStagnationTermination(expectedStagnantGenerationsNumber: 5);

            _geneticAlgorithms.Add(key: Key, value: ga);
        }
Example #46
0
 /// <summary>
 /// Configure the Genetic Algorithm.
 /// </summary>
 /// <param name="ga">The genetic algorithm.</param>
 public virtual void ConfigGA(GeneticAlgorithm ga)
 {
 }
        private BpmSolution Evaluate(BpmGenome genome)
        {
            // start time measurement
            var startTime = DateTime.Now;

            Debug.WriteLine("Evaluating: " + genome);

            // load pain factor
            painFactor = ModelHelper.GetBpmModel().GetPainFactor();

            #region costevaluation

            // calculate all process paths
            // - splitted by XOR for dependent probabilities
            var splitterXor           = new ProcessHelper.PathSplitter(genome);
            var pathsForProbabilities = splitterXor.GetPaths();

            // remove paths with 0.0 percentage probability
            pathsForProbabilities.RemoveAll(x => x.Probability == 0);

            // calculate probabilities for each activity

            //

            // [2] Wahrscheinlichkeiten für jede Activity
            var activitieProbabilities = new HashSet <BpmnActivity>();

            var painFactorActivityAttributeCovering = false;
            var painFactorObjectDependencies        = 0;

            // Calculate probabilities for every activity
            CalculateActivityProbabilities(ref activitieProbabilities, pathsForProbabilities);

            // Check resulting probabilities with input data
            painFactorActivityAttributeCovering = !CheckActivityAttributeCovering(genome.RootGene);

            // Check input/ouput realtionships from activities to objects
            //painFactorObjectDependencies = !CheckObjectDependencies();
            var valide = ProcessHelper.Validator.ValidateGenome(genome, ref painFactorObjectDependencies);

            // Calculate µNPV
            var mueP   = CalculateMueP(valide, activitieProbabilities);
            var mueNpv = CalculateMueNpv(genome, mueP);

            // Calculate σ^2NPV
            var sigma2P   = CalculateSigma2P(mueP, activitieProbabilities, pathsForProbabilities);
            var sigma2Npv = CalculateSigma2Npv(sigma2P);

            // Calculate preference function
            var costFitness = mueNpv - ModelHelper.GetBpmModel().GetAlpha() / 2 * sigma2Npv;

            Debug.WriteLine("costFitness: " + costFitness + " = " + mueNpv + " - (" +
                            ModelHelper.GetBpmModel().GetAlpha() + "/2) * " + sigma2Npv);

            #endregion

            #region timeevaluation

            double timeFitness = 0;
            foreach (var bpa in DataHelper.ActivityAttributeHelper.Instance().GetAll())
            {
                timeFitness += bpa.DecisionProbability * CalculateTime(bpa, genome.RootGene);
            }

            if (DataHelper.ActivityAttributeHelper.Instance().GetAll().Count <= 0)
            {
                timeFitness = TreeHelper.CalculateLongestTime(genome.RootGene);
            }
            #endregion

            #region fitness merge

            var fitness = costFitness * ModelHelper.GetBpmModel().GetCostWeight();
            fitness += -1 * timeFitness * ModelHelper.GetBpmModel().GetTimeWeight();

            #endregion

            if (painFactorActivityAttributeCovering)
            {
                fitness -= ModelHelper.GetBpmModel().GetPainFactor();
            }
            if (painFactorObjectDependencies > 0)
            {
                fitness -= ModelHelper.GetBpmModel().GetPainFactor() * painFactorObjectDependencies;
            }

            // only when pretty process enabled
            if (pretty)
            {
                fitness -= ModelHelper.GetBpmModel().GetPainFactor() * ProcessHelper.PrettyPrint.Check(genome);
            }

            var endTime = DateTime.Now;

            var activities = activitieProbabilities.Select(x => x.Name).Distinct().ToList();

            var index = GeneticAlgorithm.Instance()?.Population?.CurrentGeneration?.GenerationIndex;

            if (!index.HasValue)
            {
                index = -1;
            }

            var solution = new BpmSolution(
                (endTime - startTime).TotalMilliseconds,
                index.Value,
                fitness,
                genome.ToString(),
                valide,
                "[" + string.Join(", ", activities.ToArray()) + "]",
                mueP,
                mueNpv,
                sigma2P,
                sigma2Npv,
                timeFitness,
                costFitness
                );

            return(solution);
        }
Example #48
0
        /// <summary>
        /// Occurs when the Learn button is clicked on the Genetic Algorithm tab page.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private async void buttonLearnGenetic_Click(object sender, EventArgs e)
        {
            if (_geneticCts != null)
            {
                buttonLearnGenetic.Enabled = false;
                buttonLearnGenetic.Text    = "Stopping";

                _geneticCts.Cancel();

                return;
            }

            _geneticCts = new CancellationTokenSource();

            groupBoxGeneticParams.Enabled = groupBoxGeneticSolution.Enabled = false;
            buttonLearnGenetic.Text       = "Stop";

            var iterations     = (int)numericUpDownGeneticIterations.Value;
            var population     = (int)numericUpDownGeneticPopulation.Value;
            var inputCount     = (int)numericUpDownGeneticInputs.Value;
            var predCount      = (int)numericUpDownGeneticPredictions.Value;
            var shuffle        = checkBoxGeneticShuffle.Checked;
            var geneType       = (GeneticAlgorithm.GeneFunctions)comboBoxGeneticFuncs.SelectedIndex;
            var selectionType  = (GeneticAlgorithm.Selections)comboBoxGeneticSelection.SelectedIndex;
            var chromosomeType = (GeneticAlgorithm.Chromosomes)comboBoxGeneticChromosome.SelectedIndex;

            var data = PrepareData(numericUpDownGeneticSampleCount.Value, numericUpDownGeneticSampleOffset.Value, numericUpDownGeneticInputs.Value, comboBoxGeneticDataSet.SelectedItem);

            var constants      = new[] { data.Item2.Min(), data.Item2.Average(), data.Item2.Max() };
            var solution       = new double[data.Item2.Length - inputCount];
            var predictions    = new double[predCount != 0 ? predCount + inputCount : 0];
            var bestChromosome = "";
            var errorLearn     = 0.0;
            var trainRes       = false;

            progressBarGeneticLearn.Value   = 0;
            progressBarGeneticLearn.Maximum = iterations;

            await Task.Run(() =>
            {
                try
                {
                    trainRes = GeneticAlgorithm.TrainAndEval(data.Item2, ref solution, ref bestChromosome, ref errorLearn, ref predictions, iterations, population, inputCount, shuffle, constants, geneType, chromosomeType, selectionType, _geneticCts.Token, p => Invoke(new Action <int>(pi => progressBarGeneticLearn.Value = pi), p));
                }
                catch
                {
                    trainRes = false;
                }
            });

            _geneticCts = null;

            buttonLearnGenetic.Text       = "Learn";
            groupBoxGeneticParams.Enabled = groupBoxGeneticSolution.Enabled = buttonLearnGenetic.Enabled = true;

            if (!trainRes)
            {
                return;
            }

            textBoxGeneticLearnError.Text = errorLearn.ToString("0.0000") + "%";
            textBoxGeneticSolution.Text   = Utils.ResolveChromosome(bestChromosome);

            AddToChart("GA", data.Item1.AddDays(inputCount - 1), solution);

            if (predCount != 0)
            {
                textBoxGeneticPredError.Text = CalculateError(comboBoxGeneticDataSet.SelectedItem, data.Item1.AddDays(solution.Length - 1), predictions.Skip(inputCount - 1)).ToString("0.0000") + "%";

                AddToChart("GA (Pred.)", data.Item1.AddDays(inputCount - 1).AddDays(solution.Length - 1), predictions.Skip(inputCount - 1));
            }
        }
Example #49
0
    private void setupUI()
    {
        //pull info from input fields
        //ga
        populationSize        = int.Parse(populationField.text);
        numParents            = int.Parse(numParentsField.text);
        numCrossoverPoints    = int.Parse(numCrossoverPointsField.text);
        mutationChance        = float.Parse(mutationChanceField.text);
        environmentalPressure = float.Parse(environmentalPressureField.text);
        eliteFraction         = float.Parse(eliteFractionField.text);
        tournamentSize        = int.Parse(tournamentSizeField.text);
        //nn
        numHiddenLayers = int.Parse(numHiddenLayersField.text);
        hiddenLayerSize = int.Parse(hiddenLayerSizeField.text);
        numPoints       = int.Parse(numPointsField.text);
        numTestPoints   = int.Parse(numTestPointsField.text);

        switch (functionDropdown.value)//convert dropdown value to function name
        {
        case 0:
            function = "constant";
            break;

        case 1:
            function = "linear";
            break;

        case 2:
            function = "negativeLinear";
            break;

        case 3:
            function = "piecewiseLinear";
            break;

        case 4:
            function = "quadratic";
            break;

        case 5:
            function = "cubic";
            break;

        case 6:
            function = "squareRoot";
            break;

        case 7:
            function = "sine";
            break;

        case 8:
            function = "cosine";
            break;

        default:
            function = "null";
            break;
        }

        functionContent.text = function;

        //generate test inputs and outputs from correct function and based on numTestPoints
        testInputSets  = new double[numTestPoints, 1];
        testOutputSets = new double[numTestPoints, 1];
        for (int i = 0; i <= numTestPoints - 1; i++)
        {
            testInputSets[i, 0]  = (float)i / (float)(numTestPoints - 1f);
            testOutputSets[i, 0] = functionEvaluate((float)testInputSets[i, 0]);
        }

        NeuralNet net = new NeuralNet(1, 1, numHiddenLayers, hiddenLayerSize, testInputSets, testOutputSets);//create net with test sets filled

        ga = new GeneticAlgorithm(net, populationSize, numParents, environmentalPressure, eliteFraction, numCrossoverPoints, mutationChance, tournamentSize);
        isGAInitialized           = true;
        bestNet                   = (NeuralNet)ga.individuals[0];
        visualNet.net             = bestNet;
        visualNet.layerSeparation = vNetXArea / (numHiddenLayers + 1);
        visualNet.nodeSeparation  = vNetYArea / (hiddenLayerSize + 1);
        visualNet.Initialize();

        targetFunctionLine = new VectorLine("targetFunctionLine", new List <Vector2>(), 2.0f, LineType.Continuous);
        NNFunctionLine     = new VectorLine("NNFunctionLine", new List <Vector2>(), 2.0f, LineType.Points);
        fitnessHistoryLine = new VectorLine("fitnessHistoryLine", new List <Vector2>(), 2.0f, LineType.Continuous);
        VectorLine fitHistAxesLine = new VectorLine("fitHistAxesLine", new List <Vector2>(), 2.0f, LineType.Continuous);

        fitHistAxesLine.points2.Add(new Vector2(495, 230));
        fitHistAxesLine.points2.Add(new Vector2(495, 25));
        fitHistAxesLine.points2.Add(new Vector2(900, 25));

        drawTargetFunction();
        drawNNFunction();
        drawFitnessHistory();
        fitHistAxesLine.Draw();

        NNInputField.text = "0";
        updateNNOutput();
    }
Example #50
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            Models.Instance i = new Models.Instance();
            i.Days    = 7;
            i.Doctors = doctors;

            int min = (int)numMin.Value;
            int max = (int)numMax.Value;

            var        chromosome = new Models.Chromosome(21, i, r);
            var        population = new Population(min, max, chromosome);
            var        fitness    = new Models.Fitness();
            IMutation  mutation   = new TworsMutation();
            ISelection selection  = new RouletteWheelSelection();
            ICrossover crossover  = new OnePointCrossover(r.Next(20));

            if (cbxMutation.SelectedItem.ToString() == "Insertion")
            {
                mutation = new InsertionMutation();
            }
            else if (cbxMutation.SelectedItem.ToString() == "Partial Shuffle")
            {
                mutation = new PartialShuffleMutation();
            }
            else if (cbxMutation.SelectedItem.ToString() == "Reverse Sequence")
            {
                mutation = new ReverseSequenceMutation();
            }

            if (cbxSelection.SelectedItem.ToString() == "Elitizam")
            {
                selection = new EliteSelection();
            }

            if (cbxCrossover.SelectedItem.ToString() == "Two-point")
            {
                int p1 = r.Next(19);
                int p2 = r.Next(p1 + 1, 20);
                crossover = new TwoPointCrossover(p1, p2);
            }
            else if (cbxCrossover.SelectedItem.ToString() == "Uniform")
            {
                crossover = new UniformCrossover();
            }

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);

            ITermination termination = new FitnessStagnationTermination(50);

            if (cbxTermination.SelectedItem.ToString() == "Generation number")
            {
                termination = new GenerationNumberTermination(200);
            }

            ga.Termination = termination;

            ga.MutationProbability = (float)numProbability.Value;

            ga.Start();

            Gene[] g = ga.BestChromosome.GetGenes();

            dataView.Rows.Clear();
            for (int j = 0; j < 7; j++)
            {
                string[] row = new string[] { ((List <int>)g[j * 3].Value)[0].ToString() + "   " + ((List <int>)g[j * 3].Value)[1].ToString(),
                                              ((List <int>)g[j * 3 + 1].Value)[0].ToString() + "   " + ((List <int>)g[j * 3 + 1].Value)[1].ToString(),
                                              ((List <int>)g[j * 3 + 2].Value)[0].ToString() + "   " + ((List <int>)g[j * 3 + 2].Value)[1].ToString() };

                dataView.Rows.Add(row);
                dataView.Rows[j].HeaderCell.Value = (j + 1).ToString();
            }

            lblFitness.Text = ga.BestChromosome.Fitness.ToString() + "  , generacija broj " + ga.GenerationsNumber.ToString();
        }
Example #51
0
 protected virtual void AssertMutation(GeneticAlgorithm ga)
 {
     ga.Mutation.Should().BeOfType <ReverseSequenceMutation>();
 }
 public NeuralNetworkPopulation(GeneticAlgorithm geneticAlgorithm, List <NeuralNetwork> population)
 {
     GeneticAlgorithm = geneticAlgorithm;
     Population       = population;
 }
Example #53
0
        public void TSPTaskTest()
        {
            TSPTask task = new TSPTask();

            Debug.WriteLine("Точки:");
            HashSet <double> seriesSet = new HashSet <double>();
            int temp = 1;

            foreach (var p in task.Points)
            {
                Debug.WriteLine("{0}\t{1}", p.X, p.Y);
                seriesSet.Add(temp++);
            }
            Trace.WriteLine("");

            seriesSet.Remove(1);
            var series = new UniqueSeriesGenerator(seriesSet).Generate(CHROMOSOMES);

            GeneticAlgorithm alg = DefaultGeneticAlgorithmFactory.Create(TOWNS - 1, CHROMOSOMES);

            alg.Config.AllowFloat               = false;
            alg.Config.RandomInit               = false;
            alg.Config.MinGen                   = 2;
            alg.Config.MaxGen                   = TOWNS;
            alg.Cancellation.FitnessNoChange    = 5;
            alg.Config.Mutation.MutationPercent = 0.05;

            alg.Config.CrossesNumber = 100;

            alg.Algorithm.Crossing = new OnePointCross(true);
            alg.Algorithm.Casting  = new Unification(seriesSet);
            alg.Algorithm.Mutation = new SwapMutation();
            alg.Algorithm.Task     = task;

            for (int i = 0; i < series.Length; i++)
            {
                alg.CurrentGeneration.Chromosome[i] = new Chromosome(TOWNS - 1)
                {
                    Gen = series[i]
                };
            }

            alg.OnIterate += Alg_OnIterate;
            alg.Start();

            Trace.WriteLine("");

            for (int i = 0; i < task.Dimension.GetLength(0); i++)
            {
                for (int j = 0; j < task.Dimension.GetLength(1); j++)
                {
                    Trace.Write(task.Dimension[i, j] + "\t");
                }
                Trace.WriteLine("");
            }

            Trace.WriteLine("");

            for (int i = 0; i < alg.Result.Data[0].Chromosome[0].Gen.Length; i++)
            {
                int num = (int)alg.Result.Data[0].Chromosome[0].Gen[i];
                Trace.WriteLine($"{task.Points[num-1].X}\t{task.Points[num-1].Y}");
            }
            Trace.WriteLine("");
            for (int i = 0; i < alg.CurrentGeneration.Chromosome[0].Gen.Length; i++)
            {
                int num = (int)alg.CurrentGeneration.Chromosome[0].Gen[i];
                Trace.WriteLine($"{task.Points[num - 1].X}\t{task.Points[num - 1].Y}");
            }
            Trace.WriteLine("");
        }
Example #54
0
    // To be called when the genetic algorithm was terminated
    private void OnGATermination(GeneticAlgorithm ga)
    {
        AllAgentsDied -= ga.EvaluationFinished;

        RestartAlgorithm(5.0f);
    }
Example #55
0
        public static wynikGA Genetic(int counter, Item[] dane, double back_volume)
        {
            double[] minValue       = new double[counter];
            double[] maxValue       = new double[counter];
            int[]    totalBits      = new int[counter];
            int[]    fractionDigits = new int[counter];


            for (int i = 0; i < counter; i++)
            {
                minValue[i]       = 0;
                maxValue[i]       = 1;
                totalBits[i]      = 16;
                fractionDigits[i] = 4;
            }

            var selection  = new TournamentSelection(50, true);
            var crossover  = new TwoPointCrossover();
            var mutation   = new FlipBitMutation();
            var chromosome = new FloatingPointChromosome(minValue, maxValue, totalBits, fractionDigits);
            // var fitobj = new MyProblemFitness(dane, chromosome, back_volume);
            //var fitness = fitobj.Evaluate;
            var population = new Population(500, 500, chromosome);

            var fitness = new FuncFitness((c) =>
            {
                var fc = c as FloatingPointChromosome;
                //var _items = dane;
                //var _bvol = back_volume;

                /* var values = fc.ToFloatingPoints();
                 * var x1 = values[0];
                 * var y1 = values[1];
                 * var x2 = values[2];
                 * var y2 = values[3];
                 * return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
                 *
                 */

                //chromosome.ReplaceGenes(0, chromosome.GetGenes());
                double[] proc_wag          = fc.ToFloatingPoints();
                double suma_spakowanych    = 0;
                double wartosc_spakowanych = 0;
                for (int i = 0; i < proc_wag.Length; i++)
                {
                    suma_spakowanych    += dane[i].item_volume * proc_wag[i];
                    wartosc_spakowanych += dane[i].item_value * proc_wag[i];
                }

                if (suma_spakowanych <= back_volume)
                {
                    double temp = (wartosc_spakowanych * (suma_spakowanych / back_volume));
                    if (temp < 0)
                    {
                        if (Experiments.doOutput)
                        {
                            System.Console.WriteLine("LOL ");
                        }
                    }
                }


                return((suma_spakowanych <= back_volume) ? (wartosc_spakowanych * (suma_spakowanych / back_volume)) : (-suma_spakowanych));
            });



            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);

            ga.Termination = new GenerationNumberTermination(100);

            if (Experiments.doOutput)
            {
                System.Console.WriteLine("GA running...");
            }
            ga.MutationProbability  = 0.05f;
            ga.CrossoverProbability = 0.20f;
            //ga.Selection.
            ga.Start();

            // FITNESS  if (Experiments.doOutput) System.Console.WriteLine("Best solution found has fitness = " + ga.BestChromosome.Fitness);
            wynikGA w = new wynikGA();

            w.ga = ga;
            w.ch = chromosome;
            w.ch.ReplaceGenes(0, ga.BestChromosome.GetGenes());

            return(w);
        }
 void Start()
 {
     randome = new System.Random();
     //make instance  ga of getiticalgorithm class
     ga = new GeneticAlgorithm <Gene>(populationSize, total, randome, GetRandomQuestion, FitnessFunction, elitism, mutationRate);
 }
Example #57
0
        private void internalInit()
        {
#if DEBUG
            if (hasChanged)
                Debug.WriteLine("a property has changed. We recreate a genetic algorithm");
#endif
            if (_ga != null)
            {
                _ga.OnRunComplete -= Ga_OnRunComplete;
                _ga = null;
            }
            _ga = new GeneticAlgorithm(initialPopulation, FitnessFunction ?? CalculateFitness);
            _ga.OnRunComplete += Ga_OnRunComplete;
            _ga.Operators.Add(eliteOperator);
            _ga.Operators.Add(crossoverOperator);
            _ga.Operators.Add(mutateOperator);
            hasChanged = false;
        }
        public static void BuildTestGA()
        {
            //Create chromosome length = 20
            BinaryChromosome chrom = new BinaryChromosome(20);

            //Create population = [2,100]
            var population = new Population(2, 100, chrom);

            //Console.WriteLine(chrom.Length);
            //Console.WriteLine(chrom.ToString());

            //create Fitness Function (функция приспособления)
            var fitness = new FuncFitness(
                (c) =>
            {
                var fc        = c as BinaryChromosome;
                double result = 0.0;
                foreach (Gene gene in fc.GetGenes())
                {
                    result += Convert.ToDouble(gene.Value.ToString());
                }
                return(result);
            }
                );


            //create selection
            //var selection = new EliteSelection();
            var selection = new TournamentSelection();
            //var selection = new RouletteWheelSelection();
            //var selection = new StochasticUniversalSamplingSelection();

            //create crossover
            var crossover = new UniformCrossover(0.5f);
            //var crossover = new CutAndSpliceCrossover(); //только с EliteSelection()
            //var crossover = new OnePointCrossover();
            //var crossover = new TwoPointCrossover();
            //var crossover = new CycleCrossover(); // new OrderBasedCrossover(); new OrderedCrossover(); new PositionBasedCrossover(); new PartiallyMappedCrossover(); //может использоваться только с упорядоченными хромосомами. Указанная хромосома имеет повторяющиеся гены
            //var crossover = new ThreeParentCrossover(); //ОДНУ Итерацию выполняет

            //create mutation
            var mutation = new FlipBitMutation();
            //var mutation = new UniformMutation(); //1 перегрузка принимает индексы генов для мутации, 2-я все гены мутируют
            //var mutation = new TworsMutation(); //Слабая
            //var mutation = new ReverseSequenceMutation(); //Слабая


            //create termination (Количество итераций)
            var termination = new GenerationNumberTermination(100);
            //var termination = new FitnessStagnationTermination(50);
            // var termination = new FitnessThresholdTermination(50); //Постоянно зацикливается
            //TimeSpan time = new TimeSpan(0, 0, 10); //10 секунд
            //var termination = new TimeEvolvingTermination(time);

            //Сам генетический алгоритм
            var ga = new GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation);

            ga.Termination = termination;

            Console.WriteLine("Generation:  = distance");

            var latestFitness = 0.0;

            ga.GenerationRan += (sender, e) =>
            {
                var bestChromosome = ga.BestChromosome as BinaryChromosome;
                var bestFitness    = bestChromosome.Fitness.Value;

                if (bestFitness != latestFitness)
                {
                    latestFitness = bestFitness;
                    var phenotype = bestChromosome.GetGenes();

                    //Console.WriteLine(
                    //    "Generation {0,2}: ({1},{2}),({3},{4}) = {5}",
                    //    ga.GenerationsNumber,
                    //    phenotype[0],
                    //    phenotype[1],
                    //    phenotype[2],
                    //    phenotype[3],
                    //    bestFitness
                    //);

                    Console.WriteLine("Generation {0,2}. Best Fitness = {1}", ga.GenerationsNumber, bestFitness);
                    Console.Write("Chromosome: ");

                    foreach (Gene g in phenotype)
                    {
                        Console.Write(g.Value.ToString() + "");
                    }
                    Console.WriteLine();
                }
            };

            ga.Start();
        }
Example #59
0
        static void Main(string[] args)
        {
            knapsackItems = new List <Bag.Item>();
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Map", Weight = 9, Value = 150
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Water", Weight = 153, Value = 200
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Compass", Weight = 13, Value = 35
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Sandwitch", Weight = 50, Value = 160
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Glucose", Weight = 15, Value = 60
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Tin", Weight = 68, Value = 45
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Banana", Weight = 27, Value = 60
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Apple", Weight = 39, Value = 40
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Cheese", Weight = 23, Value = 30
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Beer", Weight = 52, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Suntan Cream", Weight = 11, Value = 70
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Camera", Weight = 32, Value = 30
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "T-shirt", Weight = 24, Value = 15
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Trousers", Weight = 48, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Umbrella", Weight = 73, Value = 40
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "WaterProof Trousers", Weight = 42, Value = 70
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Note-Case", Weight = 22, Value = 80
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Sunglasses", Weight = 7, Value = 20
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Towel", Weight = 18, Value = 12
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Socks", Weight = 4, Value = 50
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Book", Weight = 30, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "waterproof overclothes ", Weight = 43, Value = 75
            });

            const double crossoverProbability = 0.65;
            const double mutationProbability  = 0.08;
            const int    elitismPercentage    = 5;

            //create the population
            var population = new Population(100, 22, false, false);

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            //subscribe to the GAs Generation Complete event
            ga.OnGenerationComplete += ga_OnGenerationComplete;

            //add the operators to the ga process pipeline
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            //run the GA
            ga.Run(TerminateAlgorithm);


            //get the best solution and print Items
            var Bestchromosome = ga.Population.GetTop(1)[0];

            //decode chromosome
            Console.WriteLine("Maximum value of knapsack contains these Items : ");
            Bag BestBag = new Bag();

            for (int i = 0; i < Bestchromosome.Count; i++)
            {
                if (Bestchromosome.Genes[i].BinaryValue == 1)
                {
                    Console.WriteLine(knapsackItems[i].ToString());
                    BestBag.AddItem(knapsackItems[i]);
                }
            }
            Console.WriteLine(" Best knapsack information:\n Total Weight : {0}   Total Value : {1} Fitness : {2}", BestBag.TotalWeight, BestBag.TotalValue, Bestchromosome.Fitness);

            Console.ReadKey();
        }
Example #60
0
        private static void Run()
        {
            Console.SetError(TextWriter.Null);
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("GeneticSharp - ConsoleApp");
            Console.ResetColor();
            Console.WriteLine("Select the sample:");

            var sampleNames = TypeHelper.GetDisplayNamesByInterface <ISampleController>();

            for (int i = 0; i < sampleNames.Count; i++)
            {
                Console.WriteLine("{0}) {1}", i + 1, sampleNames[i]);
            }

            int    sampleNumber       = 0;
            string selectedSampleName = string.Empty;

            try
            {
                sampleNumber       = Convert.ToInt32(Console.ReadLine());
                selectedSampleName = sampleNames[sampleNumber - 1];
            }
            catch (Exception)
            {
                Console.WriteLine("Invalid option.");
                return;
            }

            var sampleController = TypeHelper.CreateInstanceByName <ISampleController>(selectedSampleName);

            DrawSampleName(selectedSampleName);
            sampleController.Initialize();

            Console.WriteLine("Starting...");

            var selection  = sampleController.CreateSelection();
            var crossover  = sampleController.CreateCrossover();
            var mutation   = sampleController.CreateMutation();
            var fitness    = sampleController.CreateFitness();
            var population = new Population(100, 200, sampleController.CreateChromosome());

            population.GenerationStrategy = new PerformanceGenerationStrategy();

            var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);

            ga.Termination = sampleController.CreateTermination();

            var terminationName = ga.Termination.GetType().Name;

            ga.GenerationRan += delegate
            {
                DrawSampleName(selectedSampleName);

                var bestChromosome = ga.Population.BestChromosome;
                Console.WriteLine("Termination: {0}", terminationName);
                Console.WriteLine("Generations: {0}", ga.Population.GenerationsNumber);
                Console.WriteLine("Fitness: {0,10}", bestChromosome.Fitness);
                Console.WriteLine("Time: {0}", ga.TimeEvolving);
                Console.WriteLine("Speed (gen/sec): {0:0.0000}", ga.Population.GenerationsNumber / ga.TimeEvolving.TotalSeconds);
                sampleController.Draw(bestChromosome);
            };

            try
            {
                sampleController.ConfigGA(ga);
                ga.Start();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine();
                Console.WriteLine("Error: {0}", ex.Message);
                Console.ResetColor();
                Console.ReadKey();
                return;
            }

            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine();
            Console.WriteLine("Evolved.");
            Console.ResetColor();
            Console.ReadKey();
            Run();
        }