public void BranchAndBound_IgnoresIrrelevantDimensions(int relevantCount, int irrelevantCount) { Region bounds = new Region(relevantCount + irrelevantCount); for (int i = 0; i < bounds.Lower.Count; i++) { bounds.Lower[i] = -1000; bounds.Upper[i] = 1000; } Vector slope = Vector.Zero(relevantCount + irrelevantCount); for (int i = 0; i < slope.Count; i++) { if (i < relevantCount) { slope[i] = i + 1; } else { slope[i] = 0; } } Func <Vector, double> Evaluate = vector => vector.Inner(slope); Func <Region, double> GetUpperBound = region => region.Upper.Inner(slope); //BranchAndBound.Debug = true; Vector best = BranchAndBound.Search(bounds, Evaluate, GetUpperBound); Trace.WriteLine($"best = {best}"); }
public void RemoveCrossFromMatrixTest() { int[,] actualWeights = GenerateSampleWeights(); int[,] expectedWeights = new int[2, 2]; (var i, var j) = (1, 2); expectedWeights[0, 0] = actualWeights[0, 0]; expectedWeights[0, 1] = actualWeights[0, 1]; expectedWeights[1, 0] = actualWeights[2, 0]; expectedWeights[1, 1] = actualWeights[2, 1]; var expectedRowIndices = new[] { 0, 2 }; var expectedColumnIndices = new[] { 0, 1 }; var range = Enumerable.Range(0, 3).ToArray(); var state = new StateNode { graph = actualWeights, rowIndices = range, columnIndices = range }; BranchAndBound.UpdateStateNodeWithCrossClippedGraph(state, cutPosition: (i: i, j: j)); Assert.True(state.graph.AreDeepEqual(expectedWeights)); Assert.True(state.rowIndices.AreDeepEqual(expectedRowIndices)); Assert.True(state.columnIndices.AreDeepEqual(expectedColumnIndices)); }
public void Compare_BaB_And_LC(int n, int maxRandomValue, int repeat, double possibilityOfNull) { for (int i = 0; i < repeat; i++) { var weights = GenerateRandomGraph(n, maxRandomValue, possibilityOfNull); var lc = new LatinComposition(weights).GetShortestHamiltonianCycle(); var bb = new BranchAndBound(weights).GetShortestHamiltonianCycle(); if (lc == null && bb == null) { continue; } //var s = ""; //for (int j = 0; j < n; j++) //{ // var v = new string[n]; // for (int k = 0; k < n; k++) // { // v[k] = weights[j, k]?.ToString() ?? "-"; // } // s += string.Join(" ", v) + "\n"; //} //System.IO.File.WriteAllText("D:/1.txt", s); var lcDistance = AdjacencyMatrix.PathDistance(lc, weights); var bbDistance = AdjacencyMatrix.PathDistance(bb, weights); var msg = lcDistance == bbDistance ? "" : $"\nLC distance: {lcDistance};\nB&B distance: {bbDistance}\n" + ToString(weights); Assert.True(lcDistance == bbDistance, msg); } }
/// <summary> /// Metoda odpowiedzialna za uruchomienie testów z zadanymi parametrami /// </summary> /// <param name="size"> Rozmiar instancji(ilość miast) </param> /// <param name="minWeight"> Dolny zakres losowania wag </param> /// <param name="maxWeight"> Górny zakres losowania wag </param> /// <param name="numberOfTrials"> Ilość powtórzeń </param> /// <param name="path"> Ścieżka pliku wyjściowego </param> public static void RunTest(int size, int minWeight, int maxWeight, int numberOfTrials, string path) { string output = ""; string elapsedTime = ""; Stopwatch stopWatch = new Stopwatch(); for (int i = 0; i <= numberOfTrials; i++) { Cities cities = new Cities(size, minWeight, maxWeight, true); Console.WriteLine("Próba: " + i.ToString()); stopWatch.Start(); BranchAndBound.RunAlgorithm(cities.AdjacencyMatrix); stopWatch.Stop(); if (i != 0) { elapsedTime = stopWatch.Elapsed.TotalMilliseconds.ToString(); output += elapsedTime + Environment.NewLine; } stopWatch.Reset(); } WriteOutputToFile(path, output); }
public void ReductionTestSmall() { int[,] actualWeights = GenerateSampleWeights(); int[,] expectedWeights = new int[3, 3]; expectedWeights[0, 0] = Infinity; expectedWeights[0, 1] = 0; expectedWeights[0, 2] = 0; expectedWeights[1, 0] = 0; expectedWeights[1, 1] = Infinity; expectedWeights[1, 2] = 0; expectedWeights[2, 0] = 1; expectedWeights[2, 1] = 0; expectedWeights[2, 2] = Infinity; const int expectedReductionResult = 11; int actualReductionResult = BranchAndBound.Reduction(actualWeights); Assert.Equal(expectedReductionResult, actualReductionResult); // test does not care about the main diagonal SetMainDiagonal(actualWeights, Infinity); Assert.True(actualWeights.AreDeepEqual(expectedWeights)); }
public void ReductionTestBig() { int[,] actualWeights = GenerateMatrixWithValue(sizeN: 6, value: 0); // some random values that change nothing actualWeights[0, 2] = 3; actualWeights[1, 3] = 6; actualWeights[1, 5] = 1; actualWeights[3, 1] = 13; actualWeights[3, 5] = 3; actualWeights[5, 0] = 0; actualWeights[5, 1] = 8; // minimum value in this row - 4 actualWeights[4, 0] = Infinity; actualWeights[4, 1] = 22; actualWeights[4, 2] = Infinity; actualWeights[4, 3] = 23; actualWeights[4, 4] = Infinity; actualWeights[4, 5] = 4; const int expectedReductionResult = 4; int[,] expectedWeights = (int[, ])actualWeights.Clone(); for (int i = 0; i < 6; i++) { expectedWeights[4, i] -= expectedReductionResult; } int actualReductionResult = BranchAndBound.Reduction(actualWeights); Assert.Equal(expectedReductionResult, actualReductionResult); Assert.True(actualWeights.AreDeepEqual(expectedWeights)); }
public void BaB_Huge() { for (int i = 43; i <= 43; i++) { var weights = Compare_LC_And_BaB.GenerateRandomFullGraph(n: 43, maxRandomValue: 100); var bb = new BranchAndBound(weights).GetShortestHamiltonianCycle(); } }
// [TestMethod] public void Test5() { AdjacencyMatrix testMatrix = new AdjacencyMatrix("test5.txt"); BranchAndBound solver = new BranchAndBound(); solver.SetVariables(testMatrix); solver.Solve(); Assert.AreEqual(solver.max, 269); }
public void ErrorForFourCitiesIsSame() { bnb = new BranchAndBound(fourCities); var expectedError = Math.Abs(0 - 2) + Math.Abs(0 - 0) + Math.Abs(2 - 0) + Math.Abs(0 - 2) + Math.Abs(0 - 2) + Math.Abs(2 - 2) + Math.Abs(2 - 0) + Math.Abs(2 - 0); var actualError = bnb.CalculateError(fourCities); Assert.AreEqual(expectedError, actualError); }
public void RequestingOrderedCitiesAfterARunAsyncResultsInCorrectOrder() { bnb = new BranchAndBound(fourCities); _ = bnb.RunAsync(); var expected = orderedCities; var actual = bnb.GetBestScenarioFound(); Assert.AreEqual(expected[0], actual[0]); }
//https://github.com/sagidM/HamiltonianGraph/blob/master/src/HamiltonianGraph/BranchAndBound.cs public static bool Calculate(Graph g) { int?[,] graph = HamiltonianGraph.Utils.GraphUtil.FromMatrixFormat(GraphToStringMatrix(g)); int[] cycle = new BranchAndBound(graph).GetShortestHamiltonianCycle(); if (cycle == null) { return(false); } return(cycle.Length - 1 == g.order); }
public void MinInColumnTest() { int[,] weights = GenerateMatrixWithValue(sizeN: 4, value: Infinity); weights[1, 0] = 5; weights[3, 0] = 6; int actual = BranchAndBound.MinInColumn(weights, 0); int expected = 5; Assert.Equal(expected, actual); }
public void Test9() { AdjacencyMatrix testMatrix = new AdjacencyMatrix("test9.txt"); BranchAndBound solver = new BranchAndBound(); solver.SetVariables(testMatrix); solver.Solve(); DynamicTSP dynamicSolver = new DynamicTSP(testMatrix, 0); dynamicSolver.Solve(); Assert.AreEqual(dynamicSolver.minTourCost, solver.max); }
public static void GetShortestHamiltonianCycleTest(int testNumber) { var matrix = AdjacencyMatrix.GetGraph(testNumber); var path = new BranchAndBound(matrix.Weights).GetShortestHamiltonianCycle(); Assert.True(path.AreUnique(1, path.Length - 1), string.Join(", ", path)); var actualDistance = AdjacencyMatrix.PathDistance(path, matrix.Weights); var expectedDistance = matrix.ShortestPathDistance; Assert.Equal(expectedDistance, actualDistance); }
public override ReplState Oparate() { var solutionPath = ResultsDirPath.CombinePathWith("BranchAndBound_" + DateTime.Now.Ticks); Directory.CreateDirectory(solutionPath); Graph.WriteToFile(solutionPath.CombinePathWith("Graph.txt")); var branchAndBoundSettings = DefaultSettings ? BranchAndBoundSettings <UpperBoundScheme> .Default : GetSettings(); var branchAndBound = new BranchAndBound <PartialGraphPartition, GraphPartitionSolution, UpperBoundScheme>(PartialGraphPartition.CreateEmpty(Graph, Random)); var killTask = DistributedInt.Init(); branchAndBound.RunAsync(GraphPartitionSolution.GenerateRandom(Graph), branchAndBoundSettings, killTask, ReportSolution(solutionPath), Random); return(new PendEndingReplState(killTask)); }
static void Main(string[] args) { for (int i = 1; i < 6; i++) { BranchAndBound BranchAndBound = new BranchAndBound(); int[,] table = Common.getMatrix(Common.readDat("data/input_assign05_0" + i + ".txt")); Console.WriteLine("第" + i + "组数据结果为:"); BranchAndBound.setTable(table); BranchAndBound.branchAndBound(); BranchAndBound.display(); Console.WriteLine("\n"); } Console.ReadKey(); }
public void ManualTest() { AdjacencyMatrix testMatrix = new AdjacencyMatrix("manualTest.txt"); DynamicTSP dynamicSolver = new DynamicTSP(testMatrix, 0); BranchAndBound solver = new BranchAndBound(); solver.SetVariables(testMatrix); solver.Solve(); dynamicSolver.Solve(); for (int i = 0; i < solver.finalPath.Length; i++) { Console.WriteLine(solver.finalPath[i]); } Assert.AreEqual(dynamicSolver.minTourCost, solver.max); }
public void Compare_BaB_And_LC1(int n, int maxRandomValue, int repeat) { for (int i = 0; i < repeat; i++) { var weights = GenerateRandomFullGraph(n, maxRandomValue); var lc = new LatinComposition(weights).GetShortestHamiltonianCycle(); var bb = new BranchAndBound(weights).GetShortestHamiltonianCycle(); var lcDistance = AdjacencyMatrix.PathDistance(lc, weights); var bbDistance = AdjacencyMatrix.PathDistance(bb, weights); var msg = lcDistance == bbDistance ? "" : $"\nLC distance: {lcDistance};\nB&B distance: {bbDistance}\n" + ToString(weights); Assert.True(lcDistance == bbDistance, msg); } }
public void CrossReductionTest() { int[,] actualWeights = GenerateSampleWeights(); int[,] expectedWeights = (int[, ])actualWeights.Clone(); (var i, var j) = (1, 2); (var h, var v) = (5, 3); expectedWeights[i, 0] -= h; expectedWeights[i, 1] -= h; expectedWeights[0, j] -= v; expectedWeights[2, j] -= v; expectedWeights[i, j] = BranchAndBound.Infinity; BranchAndBound.SubstractCross(actualWeights, pos: (i, j), mins: (h, v)); Assert.True(actualWeights.AreDeepEqual(expectedWeights)); }
static void Main(string[] args) { Colorful.Console.WriteAscii("Graph Partiton", Color.CornflowerBlue); //Repl.Create().Run(); var amountOfNodes = 24; var graph = GraphBuilder.CreateSumGraph(amountOfNodes); var bAndB = new BranchAndBound <PartialGraphPartition, GraphPartitionSolution, UpperBoundScheme>( PartialGraphPartition.CreateEmpty(graph, rnd)); bAndB.Run(GraphPartitionSolution.GenerateRandom(graph), BranchAndBoundSettings <UpperBoundScheme> .Default, DistributedInt.Init(), _ => {}, rnd); Console.WriteLine("Amount of solutions: " + bAndB.AmountOfSolutions); Console.WriteLine("Expensions: "); Console.WriteLine(bAndB.LevelExpensions.AsString()); Console.WriteLine("Cutoffs: "); Console.WriteLine(bAndB.LevelCutoffs.AsString()); }
static void RunBranchAndBoundAssignment() { var costMatrix = new int[4, 4] { { 3, 5, 9, 2 }, { 9, 3, 3, 4 }, { 1, 4, 2, 6 }, { 5, 3, 7, 2 } }; var solver = new BranchAndBound(costMatrix); var solutionCost = 0; var assignment = solver.FindAssignment(out solutionCost); Console.WriteLine("Assignment cost: {0}", solutionCost); for (var agent = 0; agent < assignment.Count; agent++) { Console.WriteLine(" Agent {0}: Task {1}", agent, assignment[agent]); } }
public void RandomTest() { for (int i = 0; i < 5; i++) { AdjacencyMatrix testMatrix = new AdjacencyMatrix(8); BranchAndBound solver = new BranchAndBound(); testMatrix.GenerateRandomMatrix(); DynamicTSP dynamicSolver = new DynamicTSP(testMatrix, 0); dynamicSolver.SetVariables(testMatrix); dynamicSolver.Solve(); solver.SetVariables(testMatrix); solver.Solve(); if (((int)dynamicSolver.minTourCost != solver.max)) { testMatrix.print(); } Assert.AreEqual((int)dynamicSolver.minTourCost, solver.max); } }
public void FirstBoundTest() { AdjacencyMatrix testMatrix = new AdjacencyMatrix(4); for (int i = 0; i < 100000; i++) { BranchAndBound solver = new BranchAndBound(); testMatrix.GenerateRandomMatrix(); DynamicTSP dynamicSolver = new DynamicTSP(testMatrix, 0); solver.SetVariables(testMatrix); dynamicSolver.Solve(); solver.Solve(); if (dynamicSolver.minTourCost < solver.firstBound) { Console.WriteLine("BestTour :" + dynamicSolver.minTourCost + "<= To bound" + solver.firstBound); testMatrix.print(); dynamicSolver.printTour(); Assert.Fail(); } } }
// Measure algorithms time private static TestResult RunAlgorithms(Dataset dataSet, int measurementCount) { Console.WriteLine("{0}: starting calculating dateset {1}", DateTime.Now, dataSet.GetFilePath()); var csvBuilder = new StringBuilder(); csvBuilder.AppendLine(TestResultHelper.GetInstanceResultHeader()); var stopwatch = new Stopwatch(); double BFTotal = 0; double BandBTotal = 0; double dpTotal = 0; double reduxTotal = 0; double reduxErrSum = 0; double reduxMaxErr = 0; double greedyTotal = 0; double greedyErrSum = 0; double greedyMaxErr = 0; double ftpasTotal = 0; for (int i = 1; i <= dataSet.LastInstanceId; i++) { Console.WriteLine($"{DateTime.Now}::{dataSet.Name}::{dataSet.InstanceItemsCount}::{i}"); // Load instance and solution var instance = InstanceLoader.LoadInstanceAsync(dataSet, i); if (instance == null) { continue; } int optimalResult = InstanceLoader.LoadSolution(dataSet, i); double bruteForceTimeAvg = 0; double branchAndBoundTimeAvg = 0; double dynamicProgrammingAvg = 0; double greedyAvg = 0; double reduxAvg = 0; int[] greedyHeuristicResult = null; int[] reduxHeuristicResult = null; for (int j = 0; j < measurementCount; j++) { stopwatch.Reset(); // Start Brute Force stopwatch.Start(); var bruteForceResult = BruteForce.Solve(0, instance.Weights, instance.Prices, 0, 0, instance.MaxWeight, instance.MinPrice, new int[instance.N + 1], new int[instance.N + 1]); stopwatch.Stop(); CheckResult(instance, bruteForceResult[instance.N], optimalResult, dataSet.Name, nameof(BruteForce)); bruteForceTimeAvg += stopwatch.Elapsed.TotalMilliseconds; stopwatch.Reset(); // Start Branch and Bound stopwatch.Start(); var branchAndBoundResult = BranchAndBound.Solve(0, instance.Weights, instance.Prices, 0, 0, instance.MaxWeight, new int[instance.N + 1], new int[instance.N + 1]); //BranchAndBound.Decide(0, instance.Weights, instance.Prices, 0, 0, instance.MaxWeight, 324); stopwatch.Stop(); CheckResult(instance, branchAndBoundResult[instance.N], optimalResult, dataSet.Name, nameof(BranchAndBound)); branchAndBoundTimeAvg += stopwatch.Elapsed.TotalMilliseconds; stopwatch.Reset(); // Start Dynamic programming stopwatch.Start(); var dynamicProgrammingResult = DynamicProgramming.Solve(instance.Items, instance.MaxWeight); stopwatch.Stop(); CheckResult(instance, dynamicProgrammingResult[instance.N], optimalResult, dataSet.Name, nameof(DynamicProgramming)); dynamicProgrammingAvg += stopwatch.Elapsed.TotalMilliseconds; stopwatch.Reset(); // Start Greedy heuristic stopwatch.Start(); greedyHeuristicResult = GreedyHeuristic.Solve(instance.Items.ToList(), instance.MaxWeight); stopwatch.Stop(); //CheckResult(instance, greedyHeuristicResult[instance.N], optimalPrice, dataSet.Name, nameof(GreedyHeuristic)); greedyAvg += stopwatch.Elapsed.TotalMilliseconds; stopwatch.Reset(); // Start Redux heuristic stopwatch.Start(); reduxHeuristicResult = ReduxHeuristic.Solve(instance.Items.ToList(), instance.MaxWeight); stopwatch.Stop(); reduxAvg += stopwatch.Elapsed.TotalMilliseconds; stopwatch.Reset(); } BFTotal += Avg(bruteForceTimeAvg, measurementCount); BandBTotal += Avg(branchAndBoundTimeAvg, measurementCount); dpTotal += Avg(dynamicProgrammingAvg, measurementCount); greedyTotal += Avg(greedyAvg, measurementCount); reduxTotal += Avg(reduxAvg, measurementCount); csvBuilder.AppendLine(TestResultHelper.FormatInstanceResultRow( instance.Id, instance.N, Avg(bruteForceTimeAvg, measurementCount), Avg(branchAndBoundTimeAvg, measurementCount), Avg(dynamicProgrammingAvg, measurementCount), Avg(greedyAvg, measurementCount), Avg(reduxAvg, measurementCount), 0 )); } Console.WriteLine("{0}: calculating dataset {1} ended", DateTime.Now, dataSet.GetFilePath()); return(new TestResult { InstanceSize = dataSet.InstanceItemsCount, InstancesResults = csvBuilder.ToString(), BFTime = Avg(BFTotal, dataSet.InstancesCount), BandBTime = Avg(BandBTotal, dataSet.InstancesCount), GreedyHeuristicTime = Avg(greedyTotal, dataSet.InstancesCount), ReduxHeuristicTime = Avg(reduxTotal, dataSet.InstancesCount), DPTime = Avg(dpTotal, dataSet.InstancesCount), FTPASTime = Avg(ftpasTotal, dataSet.InstancesCount), GreedyRelErr = Avg(greedyErrSum, dataSet.InstancesCount), GreedyMaxErr = greedyMaxErr, ReduxRelErr = Avg(reduxErrSum, dataSet.InstancesCount), ReduxMaxErr = reduxMaxErr }); }
public void TestSetUp() { Graph exampleGraph = new Graph("myGraph.txt"); branchAndBound = new BranchAndBound(exampleGraph, "v1"); }
public void BaB_1x1() { var cycle = new BranchAndBound(new int?[1, 1]).GetShortestHamiltonianCycle(); Assert.Single(cycle, 0); }
public void BaB_0x0() { var actual = new BranchAndBound(new int?[0, 0]).GetShortestHamiltonianCycle(); Assert.Empty(actual); }