public PRVJTFinder(PRVJTConfig config, IRouteService routeService) { Config = config; GaFinder = new GeneticAlgorithmFinder(routeService, config.Settings); Settings = Config.Settings; RouteService = routeService; }
public void DisplacemenMutationShouldNotCreateANewRoute() { var settings = new GASettings(); var random = A.Fake <IRandom>(); var map = A.Dummy <Roteiro>(); var locals = GetLocals(8); const int indexTruck = 1, indexTruckDestination = 0, indexLocalFrom = 1, length = 2, indexLocalTo = 1; A.CallTo(() => random.NextDouble()) .ReturnsNextFromSequence(0, 1); A.CallTo(() => random.Next(A <int> ._, A <int> ._)) .ReturnsNextFromSequence( indexTruck, indexTruckDestination, indexLocalFrom, length, indexLocalTo ); var gen = new Genome(map, settings) { Trucks = new[] { new Truck { Locals = locals.Take(4).ToArray() }, new Truck { Locals = locals.Skip(4).ToArray() }, new Truck { Locals = Enumerable.Empty <Local>().ToArray() } } }; var mutate = new DisplacementMutation(settings, random); var newGen = mutate.Apply(gen); var changedLocations = new[] { locals[5], locals[6] }; newGen.Trucks[indexTruck].Locals.Should().HaveCount(2); changedLocations.Should().NotBeSubsetOf(newGen.Trucks[indexTruck].Locals); newGen.Trucks[indexTruckDestination].Locals.Should().HaveCount(6); changedLocations.Should().BeSubsetOf(newGen.Trucks[indexTruckDestination].Locals); newGen.Trucks[indexTruckDestination].Locals[1].Should().Be(changedLocations[0]); newGen.Trucks[indexTruckDestination].Locals[2].Should().Be(changedLocations[1]); newGen.Trucks[2].Locals.Should().BeEmpty(); }
public void DisplacementMutationShouldCreateANewRoute() { var settings = new GASettings(); var random = A.Fake <IRandom>(); var map = A.Dummy <Roteiro>(); var locals = GetLocals(8); const int indexTruck = 0, indexLocalFrom = 1, length = 2, indexLocalTo = 0; A.CallTo(() => random.NextDouble()) .ReturnsNextFromSequence(0, 0); A.CallTo(() => random.Next(A <int> ._, A <int> ._)) .ReturnsNextFromSequence( indexTruck, indexLocalFrom, length, indexLocalTo ); var gen = new Genome(map, settings) { Trucks = new[] { new Truck { Locals = locals.Take(4).ToArray() }, new Truck { Locals = locals.Skip(4).ToArray() }, new Truck { Locals = Enumerable.Empty <Local>().ToArray() } } }; var mutate = new DisplacementMutation(settings, random); var newGen = mutate.Apply(gen); var expectLocals = newGen.Trucks[2].Locals; var changedLocations = new[] { locals[1], locals[2] }; A.CallTo(() => random.Next(0, 0)).MustHaveHappenedOnceExactly(); newGen.Trucks[0].Locals.Should().HaveCount(2); changedLocations.Should().NotBeSubsetOf(newGen.Trucks[0].Locals); newGen.Trucks[1].Locals.Should().HaveCount(4); expectLocals.Should().HaveCount(2); expectLocals.Should().BeEquivalentTo(changedLocations, option => option.WithStrictOrdering() ); }
private static ICrossover Decide(CrossoverEnum option, GASettings settings, IRouteService service) { switch (option) { case CrossoverEnum.SubRouteInsertion: return(new SubRouteInsertionCrossover(settings, RandomSingleton.Instance, service)); } throw new Exception("No crossover selected"); }
public void InsertionMutationShouldCreateANewRoute() { var settings = new GASettings(); var random = A.Fake <IRandom>(); var map = A.Dummy <Roteiro>(); var locals = GetLocals(6); const int indexTruck = 0, indexLocalFrom = 1, indexLocalTo = 0; A.CallTo(() => random.NextDouble()) .ReturnsNextFromSequence(0, 0); A.CallTo(() => random.Next(A <int> ._, A <int> ._)) .ReturnsNextFromSequence( indexTruck, indexLocalFrom, indexLocalTo ); var gen = new Genome(map, settings) { Trucks = new[] { new Truck { Locals = locals.Take(3).ToArray() }, new Truck { Locals = locals.Skip(3).ToArray() }, new Truck { Locals = Enumerable.Empty <Local>().ToArray() } } }; var mutate = new InsertionMutation(settings, random); var newGen = mutate.Apply(gen); var expectLocals = newGen.Trucks[2].Locals; A.CallTo(() => random.Next(0, 0)).MustHaveHappenedOnceExactly(); newGen.Trucks[0].Locals.Should().HaveCount(2); newGen.Trucks[0].Locals.Should().NotContain(locals[1]); newGen.Trucks[1].Locals.Should().HaveCount(3); expectLocals.Should().ContainSingle(); expectLocals.Should().Contain(locals[1]); }
public void InsertionMutationShouldNotCreateANewRoute() { var settings = new GASettings(); var random = A.Fake <IRandom>(); var map = A.Dummy <Roteiro>(); var locals = GetLocals(6); const int indexTruck = 0, indexTruckDestination = 1, indexLocalFrom = 1, indexLocalTo = 2; A.CallTo(() => random.NextDouble()) .ReturnsNextFromSequence(0, 1); A.CallTo(() => random.Next(A <int> ._, A <int> ._)) .ReturnsNextFromSequence( indexTruck, indexTruckDestination, indexLocalFrom, indexLocalTo ); var gen = new Genome(map, settings) { Trucks = new[] { new Truck { Locals = locals.Take(3).ToArray() }, new Truck { Locals = locals.Skip(3).ToArray() }, new Truck { Locals = Enumerable.Empty <Local>().ToArray() } } }; var mutate = new InsertionMutation(settings, random); var newGen = mutate.Apply(gen); newGen.Trucks[indexTruck].Locals.Should().HaveCount(2); newGen.Trucks[indexTruckDestination].Locals.Should().HaveCount(4); newGen.Trucks[indexTruckDestination].Locals[indexLocalTo].Should().Be(locals[1]); newGen.Trucks[2].Locals.Should().BeEmpty(); }
private static IMutate Decide(MutateEnum option, GASettings settings) { switch (option) { case MutateEnum.Swap: return(new SwapMutation(settings, RandomSingleton.Instance)); case MutateEnum.Inversion: return(new InversionMutation(settings, RandomSingleton.Instance)); case MutateEnum.Insertion: return(new InsertionMutation(settings, RandomSingleton.Instance)); case MutateEnum.Displacement: return(new DisplacementMutation(settings, RandomSingleton.Instance)); } throw new Exception("No mutate passed"); }
public void SwapMutation() { var settings = new GASettings(); var random = A.Fake <IRandom>(); var map = A.Dummy <Roteiro>(); var locals = GetLocals(4); const int indexTruck1 = 0, indexTruck2 = 1, indexLocal1 = 0, indexLocal2 = 1; A.CallTo(() => random.Next(A <int> ._, A <int> ._)).ReturnsNextFromSequence(indexTruck1, indexTruck2, indexLocal1, indexLocal2); var gen = new Genome(map, settings) { Trucks = new[] { new Truck { Locals = new[] { locals[0], locals[1] } }, new Truck { Locals = new[] { locals[2], locals[3] } } } }; var mutate = new SwapMutation(settings, random); var newGen = mutate.Apply(gen); newGen.Trucks[indexTruck1].Locals[indexLocal1] .Should().BeEquivalentTo( gen.Trucks[indexTruck2].Locals[indexLocal2], o => o.WithStrictOrdering()); newGen.Trucks[indexTruck2].Locals[indexLocal2] .Should().BeEquivalentTo( gen.Trucks[indexTruck1].Locals[indexLocal1], o => o.WithStrictOrdering()); }
// Adaptive GAs // In CAGA (clustering-based adaptive genetic algorithm) void Start() { settings = GetComponent <GASettings>(); populationSize = settings.PopulationSize; nrGenerations = settings.NumberOfGenerations; blocking = settings.RunAsFastAsPossible; environment.Settings = settings; selectionStrategy.Settings = settings; matingStrategy.Settings = settings; mutationStrategy.Settings = settings; population = new Population(populationSize); selectionBuffer = new SelectionBuffer(populationSize); statistics = GetComponent <Statistics>(); if (statistics == null) { statistics = gameObject.AddComponent <Statistics>(); } statistics.Population = population; BasePhenome phenomeTemplate = Helper.InstansiateAndGet <BasePhenome>(phenomePrefab); BaseGenome genomeTemplate = phenomeTemplate.Genome; for (int i = 0; i < populationSize; i++) { BaseGenome genome = genomeTemplate.CreateRandom(); // Should be possible to generate these by hand (seeded) population[i] = new PhenomeDescription(genome); } for (int i = 0; i < populationSize; i++) { BaseGenome genome = genomeTemplate.CreateRandom(); // Should be possible to generate these by hand (seeded) selectionBuffer[i] = genome; } nextStepDelegate = NextStep; currentState = State.FitnessTest; }
public void InversionMutation() { var settings = new GASettings(); var random = A.Fake <IRandom>(); var map = A.Dummy <Roteiro>(); var locals = GetLocals(5); const int indexTruck = 0, indexLocalStart = 1, length = 3; A.CallTo(() => random.Next(A <int> ._, A <int> ._)) .ReturnsNextFromSequence( indexTruck, indexLocalStart, length ); var gen = new Genome(map, settings) { Trucks = new[] { new Truck { Locals = locals } } }; var mutate = new InversionMutation(settings, random); var newGen = mutate.Apply(gen); var genLocals = newGen.Trucks[indexTruck].Locals; var current = genLocals.Skip(indexLocalStart).Take(length).ToArray(); var expect = locals.Skip(indexLocalStart).Take(length).Reverse().ToArray(); current.Should().BeEquivalentTo(expect, o => o.WithStrictOrdering()); }
public async Task <IActionResult> Post([FromBody] RoteiroViewModel roteiro) { EnsureLoadCaches(); var settings = new GASettings(); routeService.UseCache = roteiro.UseCache; routeService.Traffic = roteiro.Traffic; var config = await roteiro.ToPRVJTConfig(routeService, settings); var finder = new PRVJTFinder(config, routeService); var result = await finder.Run(); if (result.Erro) { return(Ok(new EntregadorViewModel { Mensagem = result.Messagem })); } var viewmodel = result.ListEntregadores.Select(o => new EntregadorViewModel(o)).ToList(); try { if (!string.IsNullOrEmpty(roteiro.Name)) { this.routeService.SaveCache(roteiro.Name); } } catch { } return(Ok(viewmodel)); }
public static async Task <PRVJTConfig> GetConfigByFile(string fileName, IRouteService routeService, GASettings settings = null) { var config = new PRVJTConfig(); using (var sr = new StreamReader(fileName, Encoding.GetEncoding("ISO-8859-1"))) { var name = ReadConfig("Nome", sr); var endereco = ReadConfig("Endereco", sr); var saida = $"{DateTime.Now.Date.ToString("dd/MM/yyyy")} {ReadConfig("Saida", sr)}"; var volta = $"{DateTime.Now.Date.ToString("dd/MM/yyyy")} {ReadConfig("Volta", sr)}"; var dtsaida = DateTime.Parse(saida); var dtvolta = DateTime.Parse(volta); var entregadores = Convert.ToInt32(ReadConfig("Entregadores", sr)); var descarga = Convert.ToInt32(ReadConfig("Descarga", sr)); config.Settings = settings ?? new GASettings(); config.Settings.NumberOfTrucks = entregadores; config.Map = new Roteiro(routeService, name, endereco, dtsaida, dtvolta); config.Map.DataSaida = dtsaida; config.DtLimite = dtvolta; //Linha de titulo sr.ReadLine(); while (sr.Peek() >= 0) { var line = sr.ReadLine().Split("|").Select(o => o.Replace("\t", "")).ToList(); var map = new Local(line[0], line[1]) { Period = new Period(line[2], line[3], descarga) }; await config.Map.AddDestination(map); } } return(config); }
public DisplacementMutation(GASettings settings, IRandom random) : base(settings) { this.random = random; }
protected AbstractMutate(GASettings settings) { MutationRate = settings.MutationRate; }
protected AbstractCrossover(GASettings settings) => CrossoverRate = settings.CrossoverRate;
public SwapMutation(GASettings settings, IRandom random) : base(settings) { this.random = random; }
public static IMutate GetImplementation(MutateEnum option, GASettings settings) => Decide(option, settings);
// Adaptive GAs // In CAGA (clustering-based adaptive genetic algorithm) void Start() { settings = GetComponent<GASettings>(); populationSize = settings.PopulationSize; nrGenerations = settings.NumberOfGenerations; blocking = settings.RunAsFastAsPossible; environment.Settings = settings; selectionStrategy.Settings = settings; matingStrategy.Settings = settings; mutationStrategy.Settings = settings; population = new Population(populationSize); selectionBuffer = new SelectionBuffer(populationSize); statistics = GetComponent<Statistics>(); if (statistics == null) statistics = gameObject.AddComponent<Statistics>(); statistics.Population = population; BasePhenome phenomeTemplate = Helper.InstansiateAndGet<BasePhenome>(phenomePrefab); BaseGenome genomeTemplate = phenomeTemplate.Genome; for (int i = 0; i < populationSize; i++) { BaseGenome genome = genomeTemplate.CreateRandom(); // Should be possible to generate these by hand (seeded) population[i] = new PhenomeDescription(genome); } for (int i = 0; i < populationSize; i++) { BaseGenome genome = genomeTemplate.CreateRandom(); // Should be possible to generate these by hand (seeded) selectionBuffer[i] = genome; } nextStepDelegate = NextStep; currentState = State.FitnessTest; }
public InversionMutation(GASettings settings, IRandom random) : base(settings) { this.random = random; }
/// <summary> /// Creates a new EAX-solver. /// </summary> public EAXSolver(GASettings settings, IOperator <float, TSProblem, TSPObjective, Tour, float> mutation) : base(new TSPObjective(), new HillClimbing3OptSolver(), new EAXOperator(30, EAXOperator.EdgeAssemblyCrossoverSelectionStrategyEnum.SingleRandom, true), new TournamentSelectionOperator <TSProblem, Tour, TSPObjective, float>(10, 0.5), mutation, settings) { }
public void Should_Transfer_subroutes() { var settings = new GASettings(); var service = A.Fake <IRouteService>(); var random = A.Fake <IRandom>(); var map = A.Dummy <Roteiro>(); var locals = Enumerable.Range(0, 6).Select(e => new Local(e.ToString()) { Latitude = e, Longitude = e }).ToArray(); A.CallTo(() => service.GetRouteAsync(A <Local> ._, A <Local> ._)) .Returns(new Rota { Metros = 1 }); A.CallTo(() => service.GetRouteAsync(locals[1], locals[4])) .Returns(new Rota { Metros = 0 }).Once(); A.CallTo(() => service.GetRouteAsync(locals[3], locals[2])) .Returns(new Rota { Metros = 0 }).Once(); A.CallTo(() => random.Next(A <int> ._, A <int> ._)) .Returns(1); A.CallTo(() => random.Next(A <int> ._, A <int> ._)) .ReturnsNextFromSequence( // mon to dad 0 // indice da rota a extrair a subrota , 2 // quantidade de locais a extrais da rota , 1 // indice do primeiro local da subrota // dad to mon , 1 // indice da rota a extrair a subrota , 1 // quantidade de locais a extrais da rota , 0 // indice do primeiro local da subrota ); var mon = new Genome(map, settings) { Trucks = new[] { new Truck { Locals = new[] { locals[0], locals[1], locals[2] } }, new Truck { Locals = new[] { locals[3], locals[4], locals[5] } } } }; var dad = new Genome(map, settings) { Trucks = new[] { new Truck { Locals = new[] { locals[5], locals[4], locals[3] } }, new Truck { Locals = new[] { locals[3], locals[2], locals[1] } } } }; var cx = new SubRouteInsertionCrossover(settings, random, service); var result = cx.Make(mon, dad); result.First().Trucks[0].Locals.Should() .BeEquivalentTo(new[] { locals[5], locals[4], locals[1], locals[2], locals[3] }); result.Last().Trucks[0].Locals.Should() .BeEquivalentTo(new[] { locals[0], locals[1], locals[2], locals[3] }); }
async internal Task <PRVJTConfig> ToPRVJTConfig(ICachedRouteService routeService, GASettings settings) { var dataLimite = DateTime.Parse(DhLimite); var dataSaida = DateTime.Parse(DhSaida); var config = new PRVJTConfig { Map = new Roteiro(routeService, Origem.Endereco, Origem.Endereco, dataSaida, dataLimite), Settings = settings }; config.Map.DataSaida = dataSaida; config.DtLimite = dataLimite; config.Settings.NumberOfTrucks = NumeroEntregadores == 0 ? int.MaxValue : NumeroEntregadores; config.Settings.Mutation = Mutation; config.Settings.GenerationLimit = Generations; config.Settings.PopulationSize = Population; foreach (var item in Destinos) { var map = new Local(item.Endereco, item.Endereco) { Period = new Period(item.DhInicial, item.DhFinal, item.MinutosEspera) }; await config.Map.AddDestination(map); } return(config); }
public static ICrossover GetImplementation(CrossoverEnum option, GASettings settings, IRouteService service) => Decide(option, settings, service);
public SubRouteInsertionCrossover(GASettings settings, IRandom random, IRouteService service) : base(settings) { _random = random; this.service = service; }
public async static Task <IEnumerable <Result> > RunTest(string filename) { var ret = new List <Result>(); var http = new HttpClient(); var routeService = new CachedGoogleMatrixService(http); foreach (MutateEnum mut in Enum.GetValues(typeof(MutateEnum))) { foreach (CrossoverEnum cro in Enum.GetValues(typeof(CrossoverEnum))) { var settings = new GASettings { // Altera a configuração do GA Mutation = mut, Crossover = cro }; for (int i = 0; i < 10; i++) { var file = Path.GetFileName(filename); Console.WriteLine($"A:{file} I:{i} M:{mut} C:{cro}"); var config = await PRVJTFinder.GetConfigByFile(filename, routeService, settings); // Carrega a configuração do roteiro var finder = new PRVJTFinder(config, routeService); // Executa a divisão de rotas routeService.LoadCache(); var result = await finder.Run(); routeService.SaveCache(); if (result.Erro) { ret.Add(new Result( result.TipoErro, i, filename, result.ListEntregadores.Count(), mut, cro, result.BestGenome.Fitness )); continue; } ret.Add(new Result( result.TipoErro, i, filename, result.ListEntregadores.Count(), mut, cro, result.BestGenome.Fitness )); } } } http.Dispose(); return(ret); }