public void UndirectedSparseGraph() { TestCase testCase = new TestCase(); testCase.AddVertex("n1") .AddVertex("n2") .AddVertex("n3") .AddVertex("n4") .AddVertex("n5") .AddVertex("n6"); testCase.AddUndirectedEdge("n1", "n2", 10) .AddUndirectedEdge("n2", "n3", 8) .AddUndirectedEdge("n3", "n4", 11) .AddUndirectedEdge("n4", "n5", 6) .AddUndirectedEdge("n5", "n6", 9) .AddUndirectedEdge("n1", "n6", 3) .AddUndirectedEdge("n2", "n6", 5) .AddUndirectedEdge("n3", "n6", 18) .AddUndirectedEdge("n3", "n5", 21); var tcp = new TSP<String, EquatableEdge<String>, BidirectionalGraph<String, EquatableEdge<String>>>(testCase.Graph, testCase.GetFuncWeights()); tcp.Compute(); Assert.AreEqual(tcp.BestCost, 47); Assert.IsFalse(tcp.ResultPath.IsDirectedAcyclicGraph()); }
public void ComputeWithRoot() { var graph = new BidirectionalGraph <int, EquatableEdge <int> >(); graph.AddVertex(0); var algorithm = new TSP <int, EquatableEdge <int>, BidirectionalGraph <int, EquatableEdge <int> > >(graph, edge => 1.0); ComputeWithRoot_Test(algorithm); }
public void configureBeforeClass() { driver = Browser.getBrowser("Chrome"); loginPage = new Login(); insuranceSearch = new InsuranceSearch(); addTravelers = new AddTravelers(); tsp = new TSP(); payment = new Payment(); logout = new Logout(); }
protected override void FinishLevelSetup() { // set score variables m_bestPlayerScore = float.PositiveInfinity; m_thresholdscore = TSP.FindTSPLength(m_graph.Vertices) + 0.0001f; // use greedy tsp length as threshold m_scorekey = SceneManager.GetActiveScene().name + "score" + m_levelCounter; m_highscore = PlayerPrefs.GetFloat(m_scorekey, float.PositiveInfinity); UpdateTextField(false, -1); }
public void IsHamiltonianTest() { Assert.True(TSP.IsHamiltonian(m_graph)); Assert.False(TSP.IsHamiltonian(m_complete4)); // check edge case with <= 1 vertex var smallGraph = new AdjacencyListGraph(); smallGraph.AddVertex(new Vertex()); Assert.IsTrue(TSP.IsHamiltonian(smallGraph)); }
public void configureBeforeClass() { driver = Browser.getBrowser("Chrome"); loginPage = new Login(); invoiceTool = new InvoiceTool(); addTravelers = new AddTravelers(); externalServiceVendor = new ExternalServiceVendor(); tsp = new TSP(); payment = new Payment(); logout = new Logout(); }
public void configureBeforeClass() { driver = Browser.getBrowser("Chrome"); loginPage = new Login(); invoiceTool = new InvoiceTool(); addTravelers = new AddTravelers(); planningFeeFillDetails = new PlanningFeeFillDetails(); tsp = new TSP(); payment = new Payment(); logout = new Logout(); }
public double Eval(TSP tsp) { double value = 0; for (int i = 0; i < this.Tur.Count; i++) { value += tsp.ListaOrase[this.Tur[i]][this.Tur[(i + 1) % this.Tur.Count]]; } return(value); }
public void configureBeforeClass() { driver = Browser.getBrowser("Chrome"); loginPage = new Login(); air = new AirFlow(); flightSearchResult = new FlightSearchResult(); quote = new Quote(); reprice = new RepriceBook(); tsp = new TSP(); addTravelers = new AddTravelers(); payment = new Payment(); logout = new Logout(); }
public void GetVertexColor_Throws() { // Algorithm don't use the VerticesColors var graph = new BidirectionalGraph <int, EquatableEdge <int> >(); graph.AddVerticesAndEdge(new EquatableEdge <int>(1, 2)); var algorithm = new TSP <int, EquatableEdge <int>, BidirectionalGraph <int, EquatableEdge <int> > >(graph, _ => 1.0); algorithm.Compute(1); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Assert.Throws <VertexNotFoundException>(() => algorithm.GetVertexColor(1)); }
public DataPoints CalculateDataPoints([FromBody] AlgorithmSettings settings) { var stopwatch = new Stopwatch(); var tsp = TSP.FromFile(settings.Filename); stopwatch.Start(); var result = tsp.SolveTsp(settings); stopwatch.Stop(); Console.WriteLine("Elapsed time is {0} s", stopwatch.ElapsedMilliseconds / 1000.0); return(result); }
static private void AC(TSP tsp, int T, int NumberOfAnts, double alpha, double beta) { int t = 0; List <int> ListPositionAnts = Init(tsp.NrOrase); List <Furnica> Ants = new List <Furnica>(InitAnts(ListPositionAnts, NumberOfAnts)); double[,] Pheromone = new double[tsp.NrOrase, tsp.NrOrase]; double[,] miu = new double[tsp.NrOrase, tsp.NrOrase]; Furnica BestAnt = new Furnica { Tur = new List <int>() }; Console.Write("p: "); double p = Convert.ToDouble(Console.ReadLine()); Console.Write("Q: "); int Q = Convert.ToInt32(Console.ReadLine()); InitPheromone(Pheromone, tsp.NrOrase, tsp.NrOrase); InitMiu(miu, tsp); while (t < T) { for (int pas = 1; pas < tsp.NrOrase; pas++) { for (int k = 0; k < NumberOfAnts; k++) { if (t == 0) { Ants[k].Tur.Add(StatetransitionRule(tsp, Ants[k], Pheromone, miu, alpha, beta, pas)); } else { Ants[k].Tur[pas] = StatetransitionRule(tsp, Ants[k], Pheromone, miu, alpha, beta, pas); } } } UpdatePheromone(Pheromone, Ants, tsp, p, Q); BestAnt.Tur.Clear(); BestAnt.Tur.AddRange(DetBestAnt(Ants, tsp)); t++; } WriteAnts(Ants); WriteEvalAnts(Ants, tsp); WritePheromone(Pheromone); WriteSol(BestAnt.Tur); WriteEvalSol(BestAnt, tsp); Console.ReadKey(); }
public IActionResult Otsp([FromBody] dynamic data) { JArray array = (JArray)data; TSP_Table temp = new TSP_Table(); for (int i = 1; i < array.Count; i++) { temp.Add(new List <double>()); for (int j = 1; j < array.Count; j++) { string tempStr = array[i][j].ToString(); if (tempStr == "M") { temp[i - 1].Add(TSP.M); } else { temp[i - 1].Add(Double.Parse(tempStr)); } } } TSP tsp_solver = new TSP(); try { tsp_solver.calculatePath(temp); } catch (TSP_Exception ex) { return(Json(new { error = ex.Message })); } var resGraph = temp.ToGraph(); for (int i = 0; i < tsp_solver.Path.Count - 1; i++) { foreach (var edge in resGraph.edges) { if (edge.source == "n" + tsp_solver.Path[i] && edge.target == "n" + tsp_solver.Path[i + 1]) { edge.size = 1; edge.color = "#00FF00"; } } } return(Json(resGraph)); }
public IEnumerator goOnTour(List <GameObject> toVisit) { if (prefecture != null) { List <GameObject> toReVisit = new List <GameObject>(); toVisit.Remove(prefecture); _tour = TSP.GetItinary(prefecture, toVisit); GameObject _currentDestination; while (!_tour.IsEmpty()) { _continueTour = false; _tryAgainToVisitHome = 50; _currentDestination = _tour.Pop(); goalFA = _currentDestination.GetComponentInChildren <FreightAreaIn>(); if (goalFA != null && RoadsPathfinding.RealDistanceBetween(GetComponent <RoadRouteManager>().occupiedRoad, goalFA.road) != -1) //Il existe encore une route vers ce batiment { GetComponent <RoadRouteManager>().MoveTo(goalFA.road); yield return(new WaitUntil(() => _continueTour || goalFA == null || gameObject.GetComponent <RoadRouteManager>().occupiedRoad == goalFA.road)); if (goalFA != null && _continueTour)//On a pas pu atteindre la maison et on a choisi de la skipper { toReVisit.Add(goalFA.gameObject); } if (goalFA != null && !_continueTour) { Building building = _currentDestination.GetComponent <Building>(); if (building != null) { building.RestoreHealth(); } GetComponent <SpriteRenderer>().enabled = false;//TODO il est toujours sur la FA et donc le lock est toujours activé ! yield return(new WaitForSeconds(Random.Range(2.0f, 5.0f))); GetComponent <SpriteRenderer>().enabled = true; } } } if (toReVisit.Count != 0 && _trytoRevisitCount-- != 0) { StartCoroutine(goOnTour(toReVisit)); } else { StartCoroutine(GoBack()); } } }
public void TestWithNotGeometricGraphShouldPass() { var graph = new Dictionary <int, float[]> { { 0, new float[] { 0, 1, 4, 6 } }, { 1, new float[] { 1, 0, 2, 3 } }, { 2, new float[] { 4, 2, 0, 5 } }, { 3, new float[] { 6, 4, 5, 0 } } }; var result = new TSP().CalculateMinimalCost(4, graph); Assert.AreEqual(13, result); }
private Chromosome Evaluation(Population population) { Chromosome pBest = null; foreach (Chromosome chromosome in population.Chromosomes) { chromosome.Fitness = TSP.Objective(chromosome.Towns); if (pBest == null || chromosome.Fitness < pBest.Fitness) { pBest = (Chromosome)chromosome.Clone(); } } return(pBest); }
public void configureBeforeClass() { driver = Browser.getBrowser("Chrome"); loginPage = new Login(); cruise = new CruiseFlow(); cruiseSearchResultPage = new CruiseSearchResultPage(); cruiseTrvelerDetails = new CruiseTrvelerDetails(); cruiseCabinSelector = new CruiseCabinSelector(); tsp = new TSP(); payment = new Payment(); logout = new Logout(); }
public void TryGetDistance_Throws() { // Algorithm don't use the Distances var graph = new BidirectionalGraph <int, EquatableEdge <int> >(); graph.AddVertex(1); var algorithm = new TSP <int, EquatableEdge <int>, BidirectionalGraph <int, EquatableEdge <int> > >(graph, edge => 1.0); algorithm.Compute(1); Assert.IsFalse(algorithm.TryGetDistance(1, out double _)); var graph2 = new BidirectionalGraph <TestVertex, EquatableEdge <TestVertex> >(); var algorithm2 = new TSP <TestVertex, EquatableEdge <TestVertex>, BidirectionalGraph <TestVertex, EquatableEdge <TestVertex> > >(graph2, edge => 1.0); TryGetDistance_Throws_Test(algorithm2); }
public void Solve() { stopwatch.Start(); Population population = InitializePopulation(new Chromosome() { Towns = TSP.Towns }); pBest = Evaluation(population); Result.Add((Chromosome)pBest.Clone()); iteration = 0; Task.Run(() => GetInformation()); do { while (!Console.KeyAvailable) { if (pBest.Fitness < Result[Result.Count - 1].Fitness) { Result.Add((Chromosome)pBest); ToLog(); } Population newPopulation = SelectParents(population); while (newPopulation.Chromosomes.Count <= NumberOfPopulation) { Population matingPopulation = Selection(population); Chromosome newChromosome = CrossOver(matingPopulation); newChromosome = Mutate(newChromosome); newPopulation.Chromosomes.Add(newChromosome); } population = newPopulation; pBest = Evaluation(population); iteration++; } } while (Console.ReadKey(true).Key != ConsoleKey.Escape); stopwatch.Stop(); TSP.Towns = pBest.Towns; SaveLog(); TSP.SaveTownsToFile("output.log"); }
static private void InitMiu(double[,] miu, TSP tsp) { for (int i = 0; i < tsp.NrOrase; i++) { for (int j = 0; j < tsp.NrOrase; j++) { if (i != j) { miu[i, j] = 1 / tsp.ListaOrase[i][j]; } else { miu[i, j] = 0; } } } }
static private List <int> DetBestAnt(List <Furnica> Ants, TSP tsp) { double eval = 10000000; int index = -1; for (int i = 0; i < Ants.Count; i++) { double partial = Ants[i].Eval(tsp); if (eval > partial) { eval = partial; index = i; } } return(Ants[index].Tur); }
public void OptimizationTest() { var points = new TSP.Point[] { new TSP.Point(500, 500), new TSP.Point(2000, 250), new TSP.Point(1000, 2500), new TSP.Point(1500, 1200), new TSP.Point(2465, 1779) }; var result = new TSP().Optimization(points, startTemperature: 100, endTemperature: 0.000001); const int expectedEnergy = 7365; Assert.IsTrue((int)result.Energy == expectedEnergy, "Incorrect answer"); }
public static TSP <T, EquatableEdge <T>, BidirectionalGraph <T, EquatableEdge <T> > > CreateAlgorithmAndMaybeDoComputation <T>( [NotNull] ContractScenario <T> scenario) { var graph = new BidirectionalGraph <T, EquatableEdge <T> >(); graph.AddVerticesAndEdgeRange(scenario.EdgesInGraph.Select(e => new EquatableEdge <T>(e.Source, e.Target))); graph.AddVertexRange(scenario.SingleVerticesInGraph); double Weights(Edge <T> e) => 1.0; var algorithm = new TSP <T, EquatableEdge <T>, BidirectionalGraph <T, EquatableEdge <T> > >(graph, Weights); if (scenario.DoComputation) { algorithm.Compute(scenario.Root); } return(algorithm); }
public static (double, BidirectionalGraph <string, EquatableEdge <string> >) Get(UndirectedGraph <int, Edge <int> > graph) { var tsp = new tsp(); foreach (var v in graph.Vertices) { tsp.AddVertex(v); } foreach (var e in graph.Edges) { tsp.AddUndirectedEdge(e.Source, e.Target, 1.0); } var algorithm = new TSP <string, EquatableEdge <string>, BidirectionalGraph <string, EquatableEdge <string> > >(tsp.Graph, tsp.GetWeightsFunc()); algorithm.Compute(); return(algorithm.BestCost, algorithm.ResultPath); }
//[TestMethod] public void performanceTest() { for (int i = 0; i < 6; ++i) { int repeat = 10; long avg = 0; for (int j = 0; j < repeat; ++j) { TestCase testCase = TestCase.completeGraphTestCase((i + 1) * 5, 100000000); var tcp = new TSP <String, EquatableEdge <String>, BidirectionalGraph <String, EquatableEdge <String> > >(testCase.Graph, testCase.GetFuncWeights()); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); tcp.Compute(); stopWatch.Stop(); avg += stopWatch.ElapsedMilliseconds; } Trace.WriteLine((i + 1) * 5 + " vertices complete, avg time: " + avg / repeat); } }
static private int StatetransitionRule(TSP tsp, Furnica Ant, double[,] Pheromone, double[,] miu, double alpha, double beta, int pas) { int BestCity = 0; double rnd = new Random().NextDouble(); double[] prob = new double[tsp.NrOrase]; InitProb(prob, Pheromone, miu, Ant, alpha, beta, pas); for (int i = 0; i < prob.Length; i++) { double partialSum = InitPartialSum(prob, 0, i); if (rnd <= partialSum) { BestCity = i; break; } } return(BestCity); }
public void TryGetDistance_Throws() { // Algorithm don't use the Distances var graph = new BidirectionalGraph <int, EquatableEdge <int> >(); graph.AddVertex(1); var algorithm = new TSP <int, EquatableEdge <int>, BidirectionalGraph <int, EquatableEdge <int> > >(graph, _ => 1.0); algorithm.Compute(1); Assert.IsFalse(algorithm.TryGetDistance(1, out double _)); var graph2 = new BidirectionalGraph <TestVertex, EquatableEdge <TestVertex> >(); var algorithm2 = new TSP <TestVertex, EquatableEdge <TestVertex>, BidirectionalGraph <TestVertex, EquatableEdge <TestVertex> > >(graph2, _ => 1.0); // ReSharper disable once AssignNullToNotNullAttribute Assert.Throws <ArgumentNullException>(() => algorithm2.TryGetDistance(null, out _)); var vertex = new TestVertex(); Assert.Throws <InvalidOperationException>(() => algorithm2.TryGetDistance(vertex, out _)); }
private Population InitializePopulation(Chromosome chromosome) { Population population = new Population(); Chromosome newChromosome = chromosome; for (int i = 0; i < NumberOfPopulation; i++) { int n = newChromosome.Towns.Count; while (n > 1) { n--; int k = rnd.Next(n + 1); Town value = newChromosome.Towns[k]; newChromosome.Towns[k] = newChromosome.Towns[n]; newChromosome.Towns[n] = value; } newChromosome.Fitness = TSP.Objective(newChromosome.Towns); population.Chromosomes.Add(newChromosome); } return(population); }
public void NeighborTest() { int n = 4; int[,] adjMatrix = { { 0, 10, 15, 20 }, { 10, 0, 35, 25 }, { 15, 35, 0, 30 }, { 20, 25, 30, 0 } }; Graph graph = new Graph(); graph = graph.CreateGraph(n, adjMatrix); TSP nearestNeighbor = new TSP(); nearestNeighbor.graph = graph; nearestNeighbor.FindShortestPathFromAll(); Assert.AreEqual(80, nearestNeighbor.minDistance); }
public static (double, BidirectionalGraph <string, TaggedEdge <string, string> >) Get(UndirectedGraph <string, TaggedEdge <string, string> > graph) { var tsp = new tsp(); foreach (var v in graph.Vertices) { tsp.AddVertex(v); } foreach (var e in graph.Edges) { tsp.AddUndirectedEdge(e.Source, e.Target, double.Parse(e.Tag)); } var weightFunc = tsp.GetWeightsFunc(); var algorithm = new TSP <string, EquatableEdge <string>, BidirectionalGraph <string, EquatableEdge <string> > >(tsp.Graph, weightFunc); algorithm.Compute(); var path = algorithm.ResultPath; if (path != null) { var results = new results(); foreach (var v in path.Vertices) { results.AddVertex(v); } foreach (var e in path.Edges) { results.AddDirectedEdge(e.Source, e.Target, weightFunc(e)); } return(algorithm.BestCost, results.Graph); } else { return(algorithm.BestCost, null); } }
public static void Main(string[] args) { var files = new List <string> { "berlin52", "kroA100", "kroA150", "kroA200", "fl417" }; var stopwatch = new Stopwatch(); Console.WriteLine(""); files.ForEach(file => { var tsp = TSP.FromFile(file); stopwatch.Start(); var randomPopulation = new RandomPopulation(10000, tsp); stopwatch.Stop(); Console.WriteLine("Random for " + file); Console.WriteLine("Best: " + randomPopulation.CalculateBestDistance()); Console.WriteLine("Worst: " + randomPopulation.CalculateWorstDistance()); Console.WriteLine("Average: " + randomPopulation.CalculateAverageDistance()); Console.WriteLine("Time elapsed: " + stopwatch.ElapsedMilliseconds / 1000.0 + " s\n"); stopwatch.Start(); var greedyPopulation = new GreedyPopulation(tsp); stopwatch.Stop(); Console.WriteLine("Greedy for " + file); Console.WriteLine("Best: " + greedyPopulation.CalculateBestDistance()); Console.WriteLine("Worst: " + greedyPopulation.CalculateWorstDistance()); Console.WriteLine("Average: " + greedyPopulation.CalculateAverageDistance()); Console.WriteLine("Time elapsed: " + stopwatch.ElapsedMilliseconds / 1000.0 + " s\n"); Console.WriteLine("----------------------------\n"); }); CreateHostBuilder(args).Build().Run(); }
//[TestMethod] public void performanceTest() { for (int i = 0; i < 6; ++i) { int repeat = 10; long avg = 0; for (int j = 0; j < repeat; ++j) { TestCase testCase = TestCase.completeGraphTestCase((i + 1) * 5, 100000000); var tcp = new TSP<String, EquatableEdge<String>, BidirectionalGraph<String, EquatableEdge<String>>>(testCase.Graph, testCase.GetFuncWeights()); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); tcp.Compute(); stopWatch.Stop(); avg += stopWatch.ElapsedMilliseconds; } Trace.WriteLine((i + 1) * 5 + " vertices complete, avg time: " + avg / repeat); } }
static void Main(string[] args) { ReadCityAll(); BuildCity(); ReadBuildResort(); Node root = cities[131]; MakeNodeList( root,40); Console.WriteLine(AllNodesButRoot.Count); //var tp = new TravelPlan(cities[1]); //tp.Travel(tp.currentState, AllNodesButRoot.ElementAt(0)); //tp.Travel(tp.currentState, AllNodesButRoot.ElementAt(29)); //tp.showpastActs(); TSP tsp = new TSP(); tsp.Run(root); ; }
public void DirectedSparseGraphWithoutPath() { TestCase testCase = new TestCase(); testCase.AddVertex("n1") .AddVertex("n2") .AddVertex("n3") .AddVertex("n4") .AddVertex("n5") .AddVertex("n6"); testCase.AddDirectedEdge("n1", "n2", 10) .AddDirectedEdge("n2", "n3", 8) .AddDirectedEdge("n3", "n4", 11) .AddDirectedEdge("n4", "n5", 6) .AddDirectedEdge("n5", "n6", 9) .AddDirectedEdge("n1", "n6", 3) .AddDirectedEdge("n2", "n6", 5) .AddDirectedEdge("n3", "n6", 18) .AddDirectedEdge("n3", "n5", 21); var tcp = new TSP<String, EquatableEdge<String>, BidirectionalGraph<String, EquatableEdge<String>>>(testCase.Graph, testCase.GetFuncWeights()); tcp.Compute(); Assert.AreEqual(tcp.BestCost, Double.PositiveInfinity); Assert.IsTrue(tcp.ResultPath == null); }