private I2PIdentHash GetRandomRouter( RouletteSelection <I2PRouterInfo, I2PIdentHash> r, ConcurrentBag <I2PIdentHash> exclude, bool exploratory) { I2PIdentHash result; var me = RouterContext.Inst.MyRouterIdentity.IdentHash; if (exploratory) { var subset = RouterInfos .Where(k => !exclude.Contains(k.Key)); do { result = subset .Random() .Key; } while (result == me); return(result); } var retries = 0; bool tryagain; do { result = r.GetWeightedRandom(r.Wheel.Count() < 300 ? null : exclude); tryagain = result == me; } while (tryagain && ++retries < 20); //Logging.LogInformation( $"GetRandomRouter selected {result}: {exclude.Any( k2 => k2 == result )}" ); return(result); }
I2PIdentHash GetRandomRouter(RouletteSelection <I2PRouterInfo, I2PIdentHash> r, bool exploratory) { I2PIdentHash result; var me = RouterContext.Inst.MyRouterIdentity.IdentHash; if (exploratory) { lock ( RouterInfos ) { do { lock (r.Wheel) { result = Roulette.Wheel.Random().Id; } } while (result == me); return(result); } } do { var one = r.GetWeightedRandom(); var retries = 0; while (!Contains(one) && ++retries < 20) { one = r.GetWeightedRandom(); } result = one; } while (result == me); return(result); }
private void UpdateSelectionProbabilities() { Statistics.UpdateScore(); lock ( RouterInfos ) { Roulette = new RouletteSelection <I2PRouterInfo, I2PIdentHash>(RouterInfos.Values.Select(p => p.Key), ih => ih.Identity.IdentHash, i => Statistics[i].Score); Statistics.UpdateScoreAverages(Roulette.AverageFit, Roulette.StdDevFit); RouletteFloodFill = new RouletteSelection <I2PRouterInfo, I2PIdentHash>( RouterInfos.Where(p => p.Value.Key.Options["caps"].Contains('f')).Select(ri => ri.Value).Select(p => p.Key), ih => ih.Identity.IdentHash, i => Statistics[i].Score); RouletteNonFloodFill = new RouletteSelection <I2PRouterInfo, I2PIdentHash>( RouterInfos.Where(ri => !ri.Value.Key.Options["caps"].Contains('f')).Select(ri => ri.Value).Select(p => p.Key), ih => ih.Identity.IdentHash, i => Statistics[i].Score); DebugUtils.LogInformation("All routers"); ShowRouletteStatistics(Roulette); DebugUtils.LogInformation("Floodfill routers"); ShowRouletteStatistics(RouletteFloodFill); DebugUtils.LogInformation("Non floodfill routers"); ShowRouletteStatistics(RouletteNonFloodFill); } DebugUtils.LogDebug($"Our address: {RouterContext.Inst.ExtAddress} {RouterContext.Inst.TCPPort}/{RouterContext.Inst.UDPPort} {RouterContext.Inst.MyRouterInfo}"); }
public void Roulette() { IChromosome<int>[] a = new IChromosome<int>[] { new DigitalChromosome().GenerateFromArray(new int[] { 9, 9, 9 }), new DigitalChromosome().GenerateFromArray(new int[] { 7, 7, 7 }) }; RouletteSelection<int> selection = new RouletteSelection<int>(); IChromosome<int>[] res = selection.Select(a, x => x.ToArray().Sum(), 1); }
public static void createNewSolver(int mutationIndex, int crossoverIndex, int selectorIndex, int populationSize, float mutationChance, int timeMS, int selectorSize, float crossoverChance) { MutationType mutation = null; CrossoverType crossover = null; SelectionType selection = null; AdjacencyMatrix matrix = new AdjacencyMatrix(tspXmlFile); switch (mutationIndex) { case 0: { mutation = new InversionMutation(mutationChance); break; } case 1: { mutation = new TranspositionMutation(mutationChance); break; } } switch (crossoverIndex) { case 0: { crossover = new PMXCrossover(crossoverChance); break; } case 1: { crossover = new OXCrossover(crossoverChance); break; } } switch (selectorIndex) { case 0: { selection = new TournamentSelection(selectorSize); break; } case 1: { selection = new RouletteSelection(selectorSize); break; } } GeneticSolver solver = null;//add parameters TO DO if (mutation != null && selection != null && crossover != null) { addNewSolver(new GeneticSolver(matrix, mutation, crossover, selection, populationSize, timeMS)); } }
public void RouletteTests1() { int populationSize = 1000; file = root + "\\bays29.xml"; XDocument tspFile = XDocument.Load(file); AdjacencyMatrix testMatrix = new AdjacencyMatrix(tspFile); PMXCrossover crossover = new PMXCrossover((float)(0.80)); RouletteSelection selector = new RouletteSelection(100); InversionMutation inv = new InversionMutation((float)0.05); GeneticSolver solver = new GeneticSolver(testMatrix, inv, crossover, selector, populationSize, 10); List <Candidate> listCand = solver.randomPopulation(); listCand = selector.generateBreedingPool(listCand); }
private I2PIdentHash GetRandomRouter( RouletteSelection <I2PRouterInfo, I2PIdentHash> r, IEnumerable <I2PIdentHash> exclude, bool exploratory) { I2PIdentHash result; var me = RouterContext.Inst.MyRouterIdentity.IdentHash; var excludeset = new HashSet <I2PIdentHash>(exclude); if (exploratory) { lock ( RouterInfos ) { var subset = RouterInfos .Where(k => !excludeset.Contains(k.Key)); do { result = subset .Random() .Key; } while (result == me); return(result); } } var retries = 0; bool tryagain; do { result = r.GetWeightedRandom(excludeset); tryagain = result == me; } while (tryagain && ++retries < 20); //Logging.LogInformation( $"GetRandomRouter selected {result}: {exclude.Any( k2 => k2 == result )}" ); return(result); }
private void UpdateSelectionProbabilities() { Statistics.UpdateScore(); var havehost = RouterInfos.Values.Where(rp => rp.Router.Adresses.Any(a => a.Options.Contains("host"))); Roulette = new RouletteSelection <I2PRouterInfo, I2PIdentHash>( havehost.Select(p => p.Router), ih => ih.Identity.IdentHash, i => Statistics[i].Score); RouletteFloodFill = new RouletteSelection <I2PRouterInfo, I2PIdentHash>( FloodfillInfos.Select(rp => rp.Value.Router), ih => ih.Identity.IdentHash, i => Statistics[i].Score); RouletteNonFloodFill = new RouletteSelection <I2PRouterInfo, I2PIdentHash>( havehost.Where(ri => !ri.IsFloodfill) .Select(ri => ri.Router), ih => ih.Identity.IdentHash, i => Statistics[i].Score); Logging.LogInformation("All routers"); ShowRouletteStatistics(Roulette); Logging.LogInformation("Floodfill routers"); ShowRouletteStatistics(RouletteFloodFill); Logging.LogInformation("Non floodfill routers"); ShowRouletteStatistics(RouletteNonFloodFill); #if SHOW_PROBABILITY_PROFILE ShowProbabilityProfile(); #endif Logging.LogDebug($"Our address: {RouterContext.Inst.ExtAddress} {RouterContext.Inst.TCPPort}/{RouterContext.Inst.UDPPort} {RouterContext.Inst.MyRouterInfo}"); }
public MainForm() { Random = new Random((int)DateTime.Now.Ticks); InitializeComponent(); ant.InitializeContexts(); ant.Initialization(); refreshTimer.Start(); NeuralNetwork = new NeuralNetwork() .WithInputs(8) .WithLayerWithSeparateActivationFunction(2) .WithLayerWithSeparateActivationFunction(3) .WithOutputs(1); var options = new EnvironmentOptions { AgentsCount = 20, FoodCount = 30, FieldWidth = ant.Width, FieldHeight = ant.Height, NeuralNetwork = NeuralNetwork }; GameEnvironment = new GameEnvironment(options); var fittnessFunction = new NeuroFittnessFunction(); var selection = new RouletteSelection <Neuron>(); var crossover = new ComplexNeuroCrossover(3, true, true); var mutation = new NeuroMutation(2, 5); var terminate = new NeuroTerminate(); GeneticAlgorithm = new NeuroGeneticAlgorithm(fittnessFunction, selection, crossover, mutation, terminate, NeuralNetwork); }
I2PRouterInfo GetRandomRouterInfo(RouletteSelection <I2PRouterInfo, I2PIdentHash> r, bool exploratory) { return(this[GetRandomRouter(r, exploratory)]); }
private void ShowRouletteStatistics(RouletteSelection <I2PRouterInfo, I2PIdentHash> roulette) { if (DebugUtils.LogLevel > DebugUtils.LogLevels.Information) { return; } if (!roulette.Wheel.Any()) { return; } float Mode = 0f; var bins = 20; var hist = roulette.Wheel.Histogram(sp => sp.Fit, bins); var maxcount = hist.Max(b => b.Count); if (hist.Count() == bins && !hist.All(b => Math.Abs(b.Start) < 0.01f)) { Mode = hist.Where(b => b.Count == maxcount).First().Start + (hist[1].Start - hist[0].Start) / 2f; } DebugUtils.LogInformation(string.Format( "Roulette stats: Count {3}, Min {0:0.00}, Avg {1:0.00} ({7:0.00}), Mode {6:0.00}, Max {2:0.00}, Stddev: {5:0.00}, Skew {4:0.00}", roulette.MinFit, roulette.AverageFit, roulette.MaxFit, roulette.Wheel.Count, roulette.Wheel.Skew(sp => sp.Fit), roulette.StdDevFit, Mode, RouletteSelection <I2PRouterInfo, I2PIdentHash> .RandomFitEMA)); if (DebugUtils.LogLevel > DebugUtils.LogLevels.Debug) { return; } var ix = 0; if (maxcount > 0) { foreach (var line in hist) { var st = ""; for (int i = 0; i < (40 * line.Count) / maxcount; ++i) { st += "*"; } DebugUtils.LogDebug(String.Format("Roulette stats {0,6:#0.0} ({2,5}): {1}", line.Start, st, line.Count)); ++ix; } } var aobminval = roulette.WheelAverageOrBetter.Min(sp => sp.Fit); DebugUtils.LogDebug(String.Format("Roulette WheelAverageOrBetter count: {0}, minfit: {1}", roulette.WheelAverageOrBetter.Count(), aobminval)); var min = roulette.Wheel.Where(sp => sp.Fit == roulette.MinFit).Take(10); var avg = roulette.Wheel.Where(sp => Math.Abs(sp.Fit - roulette.AverageFit) < roulette.StdDevFit * 0.3).Take(10); var max = roulette.Wheel.Where(sp => sp.Fit == roulette.MaxFit).Take(10); if (min.Any() && avg.Any() && max.Any()) { var mins = min.Aggregate(new StringBuilder(), (l, r) => { if (l.Length > 0) { l.Append(", "); } l.Append(r.Id.Id32Short); return(l); }); var maxs = max.Aggregate(new StringBuilder(), (l, r) => { if (l.Length > 0) { l.Append(", "); } l.Append(r.Id.Id32Short); return(l); }); DebugUtils.LogDebug(String.Format("Roulette stats minfit: {0}, maxfit: {1}", mins, maxs)); DebugUtils.LogDebug("Min example: " + NetDb.Inst.Statistics[min.Random().Id].ToString()); DebugUtils.LogDebug("Med example: " + NetDb.Inst.Statistics[avg.Random().Id].ToString()); DebugUtils.LogDebug("Max example: " + NetDb.Inst.Statistics[max.Random().Id].ToString()); } }
private void ShowRouletteStatistics(RouletteSelection <I2PRouterInfo, I2PIdentHash> roulette) { if (Logging.LogLevel > Logging.LogLevels.Information) { return; } if (!roulette.Wheel.Any()) { return; } float Mode = 0f; var bins = 20; var hist = roulette.Wheel.Histogram(sp => sp.Fit, bins); var maxcount = hist.Max(b => b.Count); if (hist.Count() == bins && !hist.All(b => Math.Abs(b.Start) < 0.01f)) { Mode = hist.First(b => b.Count == maxcount).Start + (hist[1].Start - hist[0].Start) / 2f; } Logging.LogInformation( $"Roulette stats: Count {roulette.Wheel.Count()}, " + $"Min {roulette.MinFit:0.00}, " + $"Avg {roulette.AverageFit:0.00}, " + $"Mode {Mode:0.00}, Max {roulette.MaxFit:0.00}, " + $"Absdev: {roulette.AbsDevFit:0.00}, " + $"Stddev: {roulette.StdDevFit:0.00}, " + $"Skew {roulette.Wheel.Skew( sp => sp.Fit ):0.00}"); if (Logging.LogLevel > Logging.LogLevels.Debug) { return; } var ix = 0; if (maxcount > 0) { foreach (var line in hist) { var st = ""; for (int i = 0; i < (40 * line.Count) / maxcount; ++i) { st += "*"; } Logging.LogInformation($"Roulette stats {line.Start,6:#0.0} ({line.Count,5}): {st}"); ++ix; } } var delta = roulette.AbsDevFit / 20; var min = roulette.Wheel.Where(sp => Math.Abs(sp.Fit - roulette.MinFit) < delta).Take(10); var avg = roulette.Wheel.Where(sp => Math.Abs(sp.Fit - roulette.AverageFit) < delta).Take(10); var max = roulette.Wheel.Where(sp => Math.Abs(sp.Fit - roulette.MaxFit) < delta).Take(10); if (min.Any() && avg.Any() && max.Any()) { var mins = min.Aggregate(new StringBuilder(), (l, r) => { if (l.Length > 0) { l.Append(", "); } l.Append(r.Id.Id32Short); return(l); }); var maxs = max.Aggregate(new StringBuilder(), (l, r) => { if (l.Length > 0) { l.Append(", "); } l.Append(r.Id.Id32Short); return(l); }); Logging.LogDebug(String.Format("Roulette stats minfit: {0}, maxfit: {1}", mins, maxs)); var minexinst = min.Random(); var medexinst = avg.Random(); var maxexinst = max.Random(); var minex = NetDb.Inst.Statistics[minexinst.Id]; var medex = NetDb.Inst.Statistics[medexinst.Id]; var maxex = NetDb.Inst.Statistics[maxexinst.Id]; Logging.LogDebug($"Min example: Space {minexinst.Space,10:F2} {minex}"); Logging.LogDebug($"Med example: Space {medexinst.Space,10:F2} {medex}"); Logging.LogDebug($"Max example: Space {maxexinst.Space,10:F2} {maxex}"); } }
internal GeneticSolver createNewSolver(bool isMultiThread) { MutationType mutation = null; CrossoverType crossover = null; SelectionType selection = null; GeneticSolver solver = null;//add parameters TO DO AdjacencyMatrix matrix = new AdjacencyMatrix(tspXmlFile); switch (mutationIndex) { case 0: { if (!isMultiThread) { mutation = new InversionMutation(mutationChance); } else { mutation = new MultiThreadInversionMutation(mutationChance); } break; } case 1: { if (!isMultiThread) { mutation = new TranspositionMutation(mutationChance); } else { mutation = new MultiThreadTranspositionMutation(mutationChance); } break; } } switch (crossoverIndex) { case 0: { if (!isMultiThread) { crossover = new PMXCrossover(crossoverChance); } else { crossover = new MultiThreadPMXCrossover(crossoverChance); //new PMXCrossover(crossoverChance); // } break; } case 1: { if (!isMultiThread) { crossover = new OXCrossover(crossoverChance); } else { crossover = new MultiThreadOXCrossover(crossoverChance); } break; } } switch (selectorIndex) { case 0: { if (!isMultiThread) { selection = new TournamentSelection(selectorSize); } else { selection = new MultiThreadTournamentSelection(selectorSize); } break; } case 1: { if (!isMultiThread) { selection = new RouletteSelection(selectorSize); } else { selection = new MultiThreadRouletteSelection(selectorSize); } break; } } if (mutation != null && selection != null && crossover != null) { if (isMultiThread) { MultiTaskOptions.parallelOptCrossover.MaxDegreeOfParallelism = int.Parse(View.tbxLvlCrossover.Text); MultiTaskOptions.parallelOptMutation.MaxDegreeOfParallelism = int.Parse(View.tbxLvlMutation.Text); MultiTaskOptions.parallelOptSelection.MaxDegreeOfParallelism = int.Parse(View.tbxLvlSelector.Text); solver = new MultiTaskGeneticSolver(matrix, mutation, crossover, selection, populationSize, timeMS); } else { solver = new SingleTaskGeneticSolver(matrix, mutation, crossover, selection, populationSize, timeMS); } } return(solver); }
private void Go_Click(object sender, EventArgs e) { //initialize var int cLength = Convert.ToInt32(chromoLength.Text); EliteSelection<int> sel2 = new EliteSelection<int>(0); RouletteSelection<int> sel1 = new RouletteSelection<int>(); GreedyCrossover cros = new GreedyCrossover(-1, -1, matrix); GoldenMutation<int> mut = new GoldenMutation<int>(cLength); pop = new Population<int>(mut, cros, sel1, sel2, x => 1 / cros.CalcFitness(x), Convert.ToDouble(mProb.Text), Convert.ToDouble(cProb.Text)); maxF = new double[Convert.ToInt32(expCount.Text), Convert.ToInt32(iterCount.Text) + 1]; avgF = new double[Convert.ToInt32(expCount.Text), Convert.ToInt32(iterCount.Text) + 1]; double min = 100500; // Hi to Max )) string bestChromo = null; //experiments for (int i = 0; i < Convert.ToInt32(expCount.Text); ++i) { //initial chromosomes Trace.WriteLine("experiment #" + (i + 1).ToString()); Trace.Indent(); ChromosomesFromArray(); maxF[i, 0] = Math.Round(1 / pop.GetMaxFitness()); avgF[i, 0] = 1 / pop.GetPopulationFitness(); Trace.WriteLine("initial best fitness = " + Math.Round((1 / pop.GetMaxFitness())).ToString()); Trace.WriteLine("initial avg fitness = " + (1 / pop.GetPopulationFitness()).ToString()); Trace.WriteLine("initia;best fitness chromo = " + pop.GetMaxChromo()); // iterations for (int j = 0; j < Convert.ToInt32(iterCount.Text); ++j) { Trace.WriteLine("iteration #" + (j + 1).ToString()); Trace.Indent(); pop.Iteration(); maxF[i, j + 1] = Math.Round(1 / pop.GetMaxFitness()); avgF[i, j + 1] = 1 / pop.GetPopulationFitness(); Trace.WriteLine(" best fitness = " + Math.Round((1 / pop.GetMaxFitness())).ToString()); Trace.WriteLine("avg fitness = " + (1 / pop.GetPopulationFitness()).ToString()); Trace.WriteLine("best fitness chromo = " + pop.GetMaxChromo()); Trace.Unindent(); } if (Math.Round(1 / pop.GetMaxFitness()) < min) { min = Math.Round(1 / pop.GetMaxFitness()); bestChromo = pop.GetMaxChromo(); } Trace.Unindent(); } answer.Text = "Best Path: " + bestChromo + "Path Length" + min.ToString(); }
public Card getNextOfferedCard(PlayerType characterIn) { var card = RouletteSelection.pick(allCards.Where(c => characterIn == c.playerType && c.isStarting == false)); return((Card)(Activator.CreateInstance(card.GetType()))); }
static void Main(string[] args) { List <Criteria> criteria = fileWriterHelper.Read(); foreach (var criterium in criteria) { Console.WriteLine(criterium.ToString()); Selection selection = new Selection(); if (!string.IsNullOrEmpty(selection.ValidateCriteria(criterium))) { Console.WriteLine(selection.ValidateCriteria(criterium)); break; } Range <double> range = new Range <double>(criterium.MinRange ?? 0.0, criterium.MaxRange ?? 0.0); switch (criterium.SelectionMode) { case Criteria.SelectionModes.Contest: selection = new Contest(); if (!string.IsNullOrEmpty(selection.ValidateCriteria(criterium))) { Console.WriteLine(selection.ValidateCriteria(criterium)); break; } else { Population population = new Population(criterium.PopulationSize ?? 0, range); population.PopulationInit(); Contest.ContestSize = criterium.ContestSize ?? 0; switch (criterium.StopCriteria) { case Criteria.StopCriterias.GenerationCount: selection.DoWork(population, criterium); break; default: break; } } break; case Criteria.SelectionModes.RankedRoulette: selection = new RankedRouletteSelection(); if (!string.IsNullOrEmpty(selection.ValidateCriteria(criterium))) { Console.WriteLine(selection.ValidateCriteria(criterium)); break; } else { //todo } break; case Criteria.SelectionModes.Roulette: selection = new RouletteSelection(); if (!string.IsNullOrEmpty(selection.ValidateCriteria(criterium))) { Console.WriteLine(selection.ValidateCriteria(criterium)); break; } else { //todo } break; default: break; } //for (int i = 0; i < 1000; i++) //{ // if (i % 50 == 0) // Console.WriteLine(population.TheBestInPopulation().FunctionValue); // population = Contest.NewPopulationInit(population); //} } Console.ReadKey(); }