示例#1
0
 public TSPSolution solve(TSPInput input)
 {
     SASPlan.Domain dom = input.exportToPlanningDomain();
     createEngine(dom);
     engine.search();
     return(convertPlan(engine.getSolution(), dom, input));
 }
示例#2
0
        public static TSPInput generateHybrid(int nodesCount, int clusters, int maxWidth = 1000, int maxHeight = 1000)
        {
            r = new Random();
            TSPInput      result = TSPInput.create();
            List <double> clustersX = new List <double>(), clustersY = new List <double>();
            double        x, y;

            for (int i = 0; i < clusters; i++)
            {
                do
                {
                    x = r.NextDouble() * maxWidth - maxWidth / (2 * clusters - 1);
                    y = r.NextDouble() * maxHeight - maxHeight / (2 * clusters - 1);
                } while (x < 0 || y < 0);
                clustersX.Add(x);
                clustersY.Add(y);
            }
            for (int j = 0; j < clusters; j++)
            {
                int clusterSize = r.Next(nodesCount / (clusters - 1));
                for (int i = 0; i < clusterSize; i++)
                {
                    TSPPoint p = TSPPoint.create(clustersX[j] + r.NextDouble() * maxWidth / clusters,
                                                 clustersY[j] + r.NextDouble() * maxHeight / clusters);
                    result.addPoint(p);
                }
            }
            while (result.nodesCount < nodesCount)
            {
                TSPPoint p = TSPPoint.create(r.NextDouble() * maxWidth, r.NextDouble() * maxHeight);
                result.addPoint(p);
            }
            return(result);
        }
示例#3
0
        public static TSPInput create(Func <TSPPoint, TSPPoint, double> distanceCalculator = null)
        {
            var result = new TSPInput();

            result.distanceCalculator = distanceCalculator;
            return(result);
        }
示例#4
0
        public static TSPInput generateClustersAntiGreedy(int nodesCount, int clusters, int maxWidth = 1000, int maxHeight = 1000)
        {
            r = new Random();
            TSPInput      result = TSPInput.create();
            List <double> clustersX = new List <double>(), clustersY = new List <double>();
            double        x, y;

            for (int i = 0; i < clusters; i++)
            {
                do
                {
                    x = r.NextDouble() * maxWidth - maxWidth / (2 * clusters);
                    y = r.NextDouble() * maxHeight - maxHeight / (2 * clusters);
                } while (x < 0 || y < 0);
                clustersX.Add(x);
                clustersY.Add(y);
            }
            for (int j = 0; j < clusters; j++)
            {
                for (int i = 0; i < (nodesCount - 4) / clusters; i++)
                {
                    TSPPoint p = TSPPoint.create(clustersX[j] + r.NextDouble() * maxWidth / clusters,
                                                 clustersY[j] + r.NextDouble() * maxHeight / clusters);
                    result.addPoint(p);
                }
            }
            result.addPoint(TSPPoint.create(0, 0));
            result.addPoint(TSPPoint.create(1000, 0));
            result.addPoint(TSPPoint.create(0, 1000));
            result.addPoint(TSPPoint.create(1000, 1000));
            return(result);
        }
示例#5
0
        private PermutationStandard initialize(TSPInput input)
        {
            var result = new PermutationStandard(input);

            result.randomize();
            return(result);
        }
示例#6
0
        private void trySolve(TSPInput input, List <int> currentPart, List <int> remainning, double currentLength)
        {
            if (currentLength > best)
            {
                return;
            }

            // pokud se krizi prave pridana hrana s nejakou dalsi tak konec - v optimalnim reseni se hrany nekrizi.
            if (isCrossing(input, currentPart))
            {
                return;
            }

            if (remainning.Count == 0)
            {
                if (currentLength + input.getDistance(currentPart[currentPart.Count - 1], 0) < best)
                {
                    best = currentLength + input.getDistance(currentPart[currentPart.Count - 1], 0);
                    currentPart.CopyTo(bestSolution);
                }
                return;
            }
            for (int i = 0; i < remainning.Count; i++)
            {
                int    item     = remainning[i];
                double distance = input.getDistance(currentPart[currentPart.Count - 1], item);
                currentPart.Add(item);
                remainning.RemoveAt(i);
                trySolve(input, currentPart, remainning, currentLength + distance);
                remainning.Insert(i, item);
                currentPart.RemoveAt(currentPart.Count - 1);
            }
        }
示例#7
0
        protected double airDistance(int point1, int point2, TSPInput input)
        {
            var p1 = input.getPoint(point1);
            var p2 = input.getPoint(point2);

            return(Math.Sqrt(Math.Sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y))));
        }
示例#8
0
        protected override int findBest(int from, TSPInput input)
        {
            int    best           = -1;
            double bestEvaluation = double.MaxValue;

            foreach (var item in available)
            {
                double evaluation = input.getDistance(from, item);

                if (solvingPath)
                {
                    evaluation += airDistance(this.pathStart, item, input) / input.maximumDistance;
                    evaluation -= airDistance(this.pathEnd, item, input) / (input.maximumDistance);
                }
                if (isLeaf(item, input))
                {
                    evaluation -= input.minimumDistance;
                }

                if (evaluation < bestEvaluation)
                {
                    bestEvaluation = evaluation;
                    best           = item;
                }
            }
            return(best);
        }
示例#9
0
        private void computeSpanningTree(TSPInput input)
        {
            representatives = new int[input.nodesCount];
            for (int i = 0; i < input.nodesCount; i++)
            {
                representatives[i] = i;
            }
            successorsList = new Dictionary <int, List <int> >();
            copyEdgesLengths(input);
            int selectedEdgesCount = 0;

            for (int i = 0; i < edges.Count; i++)
            {
                if (selectedEdgesCount == input.nodesCount - 1)
                {
                    break;
                }
                int firstRepre  = findRepresentative(edges[i].from),
                    secondRepre = findRepresentative(edges[i].to);
                if (firstRepre == secondRepre)
                {
                    continue;
                }
                representatives[firstRepre] = secondRepre;
                selectedEdgesCount++;
                addEdge(edges[i]);
            }
        }
示例#10
0
        public TSPSolution solve(TSPInput input)
        {
            TSPSolution best = null;

            for (int r = 0; r < 5; ++r)
            {
                Console.WriteLine($@"== RUN:{r} ==");
                population.Clear();
                for (int i = 0; i < PopulationSize; ++i)
                {
                    population.Add(getRandomSolution(input));
                }
                run();

                var tmp = GetBest();
                Console.WriteLine($@"Distance: {tmp.totalDistance}");

                if (best == null || tmp.totalDistance < best.totalDistance)
                {
                    best = tmp;
                }
            }
            visualizer.draw(best);
            return(best);
        }
示例#11
0
        private PermutationStandard initialize2(TSPInput input)
        {
            var solver = new GreedySolver();
            var result = solver.solve(input);

            return(new PermutationStandard(result));
        }
示例#12
0
        public void draw(TSPInput inp, bool clear = true)
        {
            if (clear)
            {
                g.Clear(Color.WhiteSmoke);
            }
            xStretch = width / (inp.maxValueX + 20);
            yStretch = height / (inp.maxValueY + 20);
            if (inp.nodesCount > 2000)
            {
                nodeSize--;
            }
            if (inp.nodesCount > 10000)
            {
                nodeSize--;
            }


            for (int i = 0; i < inp.nodesCount; i++)
            {
                var node = inp.getPoint(i);
                drawNode(node);
            }
            fillNode(inp.getPoint(0), Color.Green);
            screen.Refresh();
        }
示例#13
0
        public TSPSolution solve(TSPInput input)
        {
            Console.WriteLine("Hill climbing started");
            current     = initialize(input);
            currentBest = current.convertToTSPSol();
            visualizer.draw(currentBest);
            stop = false;
            int steps = 0;

            while (!stop)
            {
                steps++;
                goOneStep();
                if (steps % 10 == 0)
                {
                    currentBest = current.convertToTSPSol();
                    visualizer.draw(currentBest);
                    Console.WriteLine("Steps: " + steps + " Best distance: " + currentBest.totalDistance);
                }
            }
            Console.WriteLine("Search ended");
            currentBest = current.convertToTSPSol();
            visualizer.draw(currentBest);
            Console.WriteLine("Steps: " + steps + " Best distance: " + currentBest.totalDistance);
            return(currentBest);
        }
示例#14
0
        public TSPSolution solve(TSPInput input)
        {
            GreedySolver s = new GreedySolver();

            best = s.solve(input).computeDistance() + 1;

            bestSolution = new int[input.nodesCount];
            List <int> current = new List <int>();

            current.Add(0);
            List <int> remaining = new List <int>();

            for (int i = 1; i < input.nodesCount; i++)
            {
                remaining.Add(i);
            }
            trySolve(input, current, remaining, 0);
            TSPSolution result = new TSPSolution(input);

            for (int i = 0; i < input.nodesCount - 1; i++)
            {
                result.setSuccessor(bestSolution[i], bestSolution[i + 1]);
            }
            result.setSuccessor(bestSolution[input.nodesCount - 1], 0);
            return(result);
        }
示例#15
0
        public virtual TSPSolution solveStartPoint(TSPInput input, int startNode)
        {
            if (input.nodesCount <= 1)
            {
                return(new TSPSolution(input));
            }

            int endnode = Enumerable.Range(0, input.nodesCount).Select(x => input.getDistance(startNode, x)).MaxWithIndex().index;

            return(solvePath(input, startNode, endnode));

            /*
             * double bestDist = double.MaxValue;
             * TSPSolution bestSolution = null;
             * for (int i = 0; i < input.nodesCount; i++)
             * {
             *      if (i == startNode)
             *              continue;
             *      var sol = solvePath(input, startNode, i);
             *      double dist = sol.totalDistance;
             *      if (dist < bestDist)
             *      {
             *              bestSolution = sol;
             *              bestDist = dist;
             *              if (dist <= input.minimumDistance * (input.nodesCount - 1))
             *                      break;
             *              //break;
             *      }
             * }
             * return bestSolution;
             */
        }
示例#16
0
        private TSPSolution solve(TSPInput input, bool hasEdge = false, int startNode = 0, int endNode = 0)
        {
            TSPSolution result = null;

            if (hasEdge)
            {
                result = new TSPSolutionPath(input, startNode, endNode);
            }
            else
            {
                result = new TSPSolution(input);
            }
            succ = new List <List <int> >();
            edge predefinedEdge = default;

            edgesUsed = 0;
            List <edge> edges = new List <edge>();

            for (int i = 0; i < input.nodesCount; i++)
            {
                succ.Add(new List <int>());
                for (int j = 0; j < i; j++)
                {
                    edge ed = new edge(i, j, input.getDistance(i, j));
                    if (hasEdge && (startNode == i && endNode == j) || (startNode == j && endNode == i))
                    {
                        predefinedEdge = ed;
                    }
                    else
                    {
                        edges.Add(ed);
                    }
                }
            }
            if (hasEdge)
            {
                addToSolution(predefinedEdge);
            }

            edges.Sort((a, b) => (int)(a.distance - b.distance));
            int index = -1;

            while (edgesUsed < input.nodesCount)
            {
                index++;
                edge e = edges[index];
                if (succ[e.node1].Count >= 2 || succ[e.node2].Count >= 2)
                {
                    continue;
                }
                if (createsCycle(e) && edgesUsed != input.nodesCount - 1)
                {
                    continue;
                }
                addToSolution(e);
            }
            addEdgesToResult(result);
            return(result);
        }
示例#17
0
 public Edge(int from, int to, TSPInput inp, double weight)
 {
     this.from   = from;
     this.to     = to;
     this.weight = weight;
     this.inp    = inp;
     this.a      = (inp.getPoint(to).y - inp.getPoint(from).y) / (inp.getPoint(to).x - inp.getPoint(from).x);
     this.b      = inp.getPoint(to).y - inp.getPoint(to).x *a;
 }
示例#18
0
 public Edge(int from, int to, TSPInput inp)
 {
     this.from   = from;
     this.to     = to;
     this.weight = inp.getDistance(from, to);
     this.inp    = inp;
     this.a      = (inp.getPoint(to).y - inp.getPoint(from).y) / (inp.getPoint(to).x - inp.getPoint(from).x);
     this.b      = inp.getPoint(to).y - inp.getPoint(to).x *a;
 }
示例#19
0
        private static TSPInput load(string file)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream     stream    = new FileStream(file, FileMode.Open);
            TSPInput   t         = (TSPInput)formatter.Deserialize(stream);

            stream.Close();
            return(t);
        }
示例#20
0
        public override TSPSolution solvePath(TSPInput input, int startNode, int endNode)
        {
            this.solvingPath = true;
            this.pathStart   = startNode;
            this.pathEnd     = endNode;
            var result = base.solvePath(input, startNode, endNode);

            solvingPath = false;
            return(result);
        }
示例#21
0
        /// <summary>
        /// Node is leaf if there is only one other node such that their distance is the minimalDistance (among all nodes)
        /// </summary>
        /// <param name="node"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        protected bool isLeaf(int node, TSPInput input)
        {
            int neighbours = available.Select(r => input.getDistance(r, node)).Where(d => d == input.minimumDistance).Count();

            if (input.getDistance(this.pathEnd, node) == input.minimumDistance)
            {
                neighbours++;
            }
            return(neighbours == 1);
        }
示例#22
0
        public TSPSolution solve(TSPInput input)
        {
            computeSpanningTree(input);
            TSPSolution result = new TSPSolution(input);

            visited.Clear();
            labelTreePreOrder(0, result);
            result.setSuccessor(lastNodeLabeled, 0);
            return(result);
            //return null;
        }
示例#23
0
        public static TSPInput generateUniform(int nodesCount, int maxWidth = 1000, int maxHeight = 1000)
        {
            //r = new Random();
            TSPInput result = TSPInput.create();

            for (int i = 0; i < nodesCount; i++)
            {
                TSPPoint p = TSPPoint.create(r.NextDouble() * maxWidth, r.NextDouble() * maxHeight);
                result.addPoint(p);
            }
            return(result);
        }
示例#24
0
 private void copyEdgesLengths(TSPInput input)
 {
     edges = new List <Edge>();
     for (int i = 0; i < input.nodesCount; i++)
     {
         for (int j = i + 1; j < input.nodesCount; j++)
         {
             edges.Add(new Edge(i, j, input, input.getDistance(i, j)));
         }
     }
     edges.Sort((t1, t2) => t1.weight.CompareTo(t2.weight));
 }
示例#25
0
        // Initialization of a TSPSolution
        private TSPSolution getRandomSolution(TSPInput input)
        {
            var perm = new PermutationStandard(input);

            perm.randomize();
            var p = perm.convertToTSPSol();

            if (!p.validate())
            {
                throw new InvalidOperationException();
            }
            return(p);
        }
示例#26
0
        public void findBestPermutation(TSPInput input)
        {
            inp             = input;
            bestFitness     = double.MaxValue;
            bestPermutation = new List <int>(input.nodesCount);
            List <int> available = new List <int>(input.nodesCount);

            for (int i = 1; i < input.nodesCount; i++)
            {
                available.Add(i);
            }
            searchPermutations(available, new List <int>(input.nodesCount));
        }
示例#27
0
        private TSPSolution convertPlan(List <int> plan, SASPlan.Domain domain, TSPInput input)
        {
            TSPSolution sol = new TSPSolution(input);
            int         j   = 0;

            foreach (var item in plan)
            {
                SASPlan.Operator op = domain.operators[item];
                sol.setSuccessor(j, op.effects[0].effectValue);
                j = op.effects[0].effectValue;
            }
            sol.setSuccessor(j, 0);
            return(sol);
        }
示例#28
0
        protected virtual int findBest(int from, TSPInput input)
        {
            int    best         = -1;
            double bestDistance = double.MaxValue;

            foreach (var item in available)
            {
                double distance = input.getDistance(from, item);
                if (distance < bestDistance)
                {
                    bestDistance = distance;
                    best         = item;
                }
            }
            return(best);
        }
示例#29
0
文件: TSPSolution.cs 项目: vvancak/ai
        internal static TSPSolution fromString(string result, TSPInput inp)
        {
            string[] points = result.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            if (points.Length != inp.nodesCount)
            {
                System.Windows.Forms.MessageBox.Show("Spatna delka reseni.\nReseni ma mit delku " + inp.nodesCount + ". Vase reseni ma delku " + points.Length);
                return(null);
            }
            TSPSolution sol = new TSPSolution(inp);

            for (int i = 0; i < points.Length - 1; i++)
            {
                sol.setSuccessor(int.Parse(points[i]) - 1, int.Parse(points[i + 1]) - 1);
            }
            sol.setSuccessor(int.Parse(points[points.Length - 1]) - 1, int.Parse(points[0]) - 1);
            return(sol);
        }
示例#30
0
        public TSPSolution solve(TSPInput input)
        {
            computeCentroid(input);
            int[] points = new int[input.nodesCount];
            for (int i = 0; i < input.nodesCount; i++)
            {
                points[i] = i;
            }
            Array.Sort(points, comparer);
            TSPSolution sol = new TSPSolution(input);

            for (int i = 0; i < input.nodesCount - 1; i++)
            {
                sol.setSuccessor(points[i], points[i + 1]);
            }
            sol.setSuccessor(points[input.nodesCount - 1], points[0]);
            return(sol);
        }