public void DoTest()
        {
            DirectedWeightedSparseGraph <string> graph = new DirectedWeightedSparseGraph <string>();

            // Add vertices
            var verticesSet1 = new string[] { "a", "z", "s", "x", "d", "c", "f", "v" };

            graph.AddVertices(verticesSet1);

            // Add edges
            graph.AddEdge("a", "s", 1);
            graph.AddEdge("a", "z", 1);
            graph.AddEdge("s", "x", 1);
            graph.AddEdge("x", "d", 1);
            graph.AddEdge("x", "c", 1);
            graph.AddEdge("d", "f", 1);
            graph.AddEdge("d", "c", 1);
            graph.AddEdge("c", "f", 1);
            graph.AddEdge("c", "v", 1);
            graph.AddEdge("v", "f", 1);

            // Print the nodes in graph
            Console.WriteLine(" [*] DFS PrintAll: ");
            DepthFirstSearcher.PrintAll(graph, "a");
            Console.WriteLine("\r\n");

            var list = DepthFirstSearcher.FindAllPaths(graph, "a", "f");

            foreach (var path in list)
            {
                Console.WriteLine(string.Join(",", path));
            }

            Assert.AreEqual(5, list.Count);
        }
예제 #2
0
        public void only_search_nodes_on_graph()
        {
            var a = new Vertex <string>
            {
                Value = "Cat"
            };
            var b = new Vertex <string>
            {
                Value = "Rat"
            };
            var c = new Vertex <string>
            {
                Value = "Dog"
            };
            var d = new Vertex <string>
            {
                Value = "Dog"
            };

            a.AddEdge(b);
            b.AddEdge(c);
            a.AddEdge(d);
            var graph = new Graph <string>();

            graph.AddVertex(a);
            graph.AddVertex(b);
            graph.AddVertex(c);
            var dfsSearcher = new DepthFirstSearcher <string>();

            var result = dfsSearcher.Search(graph, a, s => s == "Dog");

            result.Should().Be(c);
        }
예제 #3
0
        static void Main(string[] args)
        {
            ISearcher <Position> bfs       = new BestFirstSearcher <Position>();
            ISearcher <Position> dfs       = new DepthFirstSearcher <Position>();
            DFSMazeGenerator     mazeMaker = new DFSMazeGenerator();
            MazeWrap             m         = new MazeWrap();

            Console.WriteLine("Start {0} - End {1}", m.InitialPos.ToString(), m.GoalPos.ToString());
            Console.WriteLine("Rows {0} - Cols {1}", m.Rows, m.Cols);
            SearchableMaze maze = new SearchableMaze(m);
            Maze           k;

            maze.print();
            if (bfs.search(maze) != null)
            {
                Console.WriteLine("Number of BFS evaluations: {0}", bfs.getNumberOfEvaluations());
            }
            else
            {
                Console.WriteLine("No solution found!");
            }

            if (dfs.search(maze) != null)
            {
                Console.WriteLine("Number of DFS evaluations: {0}", dfs.getNumberOfEvaluations());
            }
            else
            {
                Console.WriteLine("No solution found!");
            }
        }
예제 #4
0
        public void BasicSearchAllTest()
        {
            DPNProblemContext   ctx     = GenerateProblemContext();
            DiscreteTimeAdapter adapter = new DiscreteTimeAdapter(ctx.StartTime, ctx.EndTime, 1);
            var graph = new BasicTravelHyperNetwork(ctx, adapter);

            graph.Build();

            var list = DepthFirstSearcher.FindAllPaths(graph,
                                                       new TravelHyperNode()
            {
                Time = 0, Station = ctx.Wor.Net.StationCollection.First(), Price = 0
            },
                                                       new TravelHyperNode()
            {
                Time = adapter.Horizon + 1440, Station = ctx.Wor.Net.StationCollection.Last(), Price = 0
            });

            foreach (var path in list)
            {
                Console.WriteLine(string.Join(",", path));
            }
            Assert.AreEqual(30, list.Count);
            //路径集
            TravelPath p = new TravelPath(graph, list[1]);

            Assert.AreEqual(ctx.Wor.Net.StationCollection.First(), p.StartStation);
        }
예제 #5
0
        private void IDNaiveButton_Click(object sender, EventArgs e)
        {
            var tree = new SearchTree <Problems.SlidingTilesPuzzle.State>(_currentState);
            var dfs  = new DepthFirstSearcher <Problems.SlidingTilesPuzzle.State, int>(
                tree,
                x => x.GetActions(),
                (x, a) => x.Clone().ApplyAction(a),
                (x, a) => 1,
                x => x.IsSolution);
            var id = new IterativeDeepeningDepthFirstSearch <Problems.SlidingTilesPuzzle.State, int>(dfs);

            var           updateCount  = 0;
            var           start        = DateTime.Now;
            Action <bool> updateCounts = (force) =>
            {
                if (!force && ++updateCount % 10000 > 0)
                {
                    return;
                }
                NodesGeneratedLabel.Text = "Generated = " + dfs.NodesGeneratedCount + " ";
                ExpandedNodesLabel.Text  = "Expanded = " + dfs.NodesExpandedCount + " ";
                RetainedNodesLabel.Text  = "Retained = " + dfs.NodesRetainedCount + " ";
                SecondsLabel.Text        = DateTime.Now.Subtract(start).TotalSeconds.ToString() + " (next depth = " + dfs.NextCostThreshhold + ")";
                _currentState            = dfs.CurrentNode.Data;
                panel1.Invalidate();
                Application.DoEvents();
            };

            dfs.NodeExpanded  += (s, a) => updateCounts(false);
            dfs.NodeGenerated += (s, a) => updateCounts(false);

            var solution = id.Search();

            updateCounts(true);
        }
예제 #6
0
        public void return_null_if_starting_vertex_not_in_graph()
        {
            var a = new Vertex <string>
            {
                Value = "Dog"
            };
            var b = new Vertex <string>
            {
                Value = "Dog"
            };
            var c = new Vertex <string>
            {
                Value = "Dog"
            };

            a.AddEdge(b);
            b.AddEdge(c);
            var graph = new Graph <string>();

            graph.AddVertex(b);
            var dfsSearcher = new DepthFirstSearcher <string>();

            var result = dfsSearcher.Search(graph, a, s => s == "Dog");

            result.Should().Be(null);
        }
        public static void DoTest()
        {
            IGraph <string> graph = new UndirectedSparseGraph <string>();

            // Add vertices
            var verticesSet1 = new string[] { "a", "z", "s", "x", "d", "c", "f", "v" };

            graph.AddVertices(verticesSet1);

            // Add edges
            graph.AddEdge("a", "s");
            graph.AddEdge("a", "z");
            graph.AddEdge("s", "x");
            graph.AddEdge("x", "d");
            graph.AddEdge("x", "c");
            graph.AddEdge("d", "f");
            graph.AddEdge("d", "c");
            graph.AddEdge("c", "f");
            graph.AddEdge("c", "v");
            graph.AddEdge("v", "f");

            // Print the nodes in graph
            Console.WriteLine(" [*] DFS PrintAll: ");
            DepthFirstSearcher.PrintAll(graph, "d");
            Console.WriteLine("\r\n");

            string             searchResult    = null;
            string             startFromNode   = "d";
            Action <string>    writeToConsole  = (node) => Console.Write(String.Format("({0}) ", node));
            Predicate <string> searchPredicate = (node) => node == "f" || node == "c";

            Console.WriteLine("[*] DFS Visit All Nodes:");
            Console.WriteLine("Graph traversal started at node: '" + startFromNode + "'");

            DepthFirstSearcher.VisitAll(ref graph, startFromNode, writeToConsole);

            Console.WriteLine("\r\n");

            try
            {
                searchResult = DepthFirstSearcher.FindFirstMatch(graph, startFromNode, searchPredicate);

                Debug.Assert(searchResult == "c" || searchResult == "f");

                Console.WriteLine("[*] DFS Find First Match:");
                Console.WriteLine(
                    String.Format(
                        "Search result: '{0}'. The search started from node: '{1}'."
                        , searchResult
                        , startFromNode));
            }
            catch (Exception)
            {
                Console.WriteLine("Search predicate was not matched by any node in the graph.");
            }

            Console.WriteLine("\r\n");
        }
예제 #8
0
 protected override void ProcessInternal(IGraph graph)
 {
     for (int i = 0; i < Vertexes; i++)
     {
         int w = r.Next(Vertexes);
         DepthFirstSearcher dfs = new DepthFirstSearcher(graph, w);
         List <int>         v   = dfs.Order;
     }
 }
예제 #9
0
 /// <summary>
 /// The constructor generates the required objects
 /// </summary>
 public MazeGameModel()
 {
     mazeMaker             = new DFSMazeGenerator();
     singlePlayerMazes     = new Dictionary <string, SearchableMaze>();
     singlePlayerSolutions = new Dictionary <string, Solution <Position> >();
     multiplayerMazes      = new Dictionary <string, MultiplayerMazeGame>();
     playerToGameMap       = new Dictionary <string, MultiplayerMazeGame>();
     bfs = new BestFirstSearcher <Position>();
     dfs = new DepthFirstSearcher <Position>();
 }
예제 #10
0
        public bool SearchDepthFirst(T thing)
        {
            if (_root == null)
            {
                return(false);
            }

            var dfs = new DepthFirstSearcher <T>();

            return(dfs.Search(_root, thing));
        }
예제 #11
0
        public void search_depth_first()
        {
            var a = new Vertex <string>
            {
                Value = "Cat"
            };
            var b = new Vertex <string>
            {
                Value = "Rat"
            };
            var c = new Vertex <string>
            {
                Value = "Dog"
            };
            var d = new Vertex <string>
            {
                Value = "Turtle"
            };
            var e = new Vertex <string>
            {
                Value = "Parrot"
            };
            var f = new Vertex <string>
            {
                Value = "Raccoon"
            };
            var g = new Vertex <string>
            {
                Value = "Dog"
            };

            a.AddEdge(b);
            b.AddEdge(c);
            a.AddEdge(d);
            d.AddEdge(e);
            e.AddEdge(f);
            f.AddEdge(g);
            var graph = new Graph <string>();

            graph.AddVertex(a);
            graph.AddVertex(b);
            graph.AddVertex(c);
            graph.AddVertex(d);
            graph.AddVertex(e);
            graph.AddVertex(f);
            graph.AddVertex(g);

            var dfsSearcher = new DepthFirstSearcher <string>();

            var result = dfsSearcher.Search(graph, a, s => s == "Dog");

            result.Should().Be(g);
        }
예제 #12
0
        public void return_starting_vertex_if_meets_criteria()
        {
            var a = new Vertex <string>
            {
                Value = "Dog"
            };
            var b = new Vertex <string>
            {
                Value = "Dog"
            };

            a.AddEdge(b);
            var graph = new Graph <string>();

            graph.AddVertex(a);
            graph.AddVertex(b);
            var dfsSearcher = new DepthFirstSearcher <string>();

            var result = dfsSearcher.Search(graph, a, s => s == "Dog");

            result.Should().Be(a);
        }
예제 #13
0
        private void DfsButton_Click(object sender, EventArgs e)
        {
            // Without any I/D or heuristics this is the same as random search

            var tree = new SearchTree <Problems.SlidingTilesPuzzle.State>(_currentState);
            var dfs  = new DepthFirstSearcher <Problems.SlidingTilesPuzzle.State, int>(
                tree,
                x => x.GetActions().RandomizeOrder(),
                (x, a) => x.ApplyAction(a), // Don't need to clone because DFS is one way
                (x, a) => 1,
                x => x.IsSolution);

            var           updateCount  = 0;
            var           start        = DateTime.Now;
            Action <bool> updateCounts = (force) =>
            {
                if (!force && ++updateCount % 10000 > 0)
                {
                    return;
                }
                NodesGeneratedLabel.Text = "Generated = " + dfs.NodesGeneratedCount + " ";
                ExpandedNodesLabel.Text  = "Expanded = " + dfs.NodesExpandedCount + " ";
                RetainedNodesLabel.Text  = "Retained = " + dfs.NodesRetainedCount + " ";
                SecondsLabel.Text        = DateTime.Now.Subtract(start).TotalSeconds.ToString();
                _currentState            = dfs.CurrentNode.Data;
                panel1.Invalidate();
                Application.DoEvents();
            };

            dfs.NodeExpanded  += (s, a) => updateCounts(false);
            dfs.NodeGenerated += (s, a) => updateCounts(false);

            var solution = dfs.Search();

            updateCounts(true);
        }
예제 #14
0
        private void button2_Click(object sender, EventArgs e)
        {
            var initialState = Enumerable.Range(0, _problem.Size).Select(x => - 1).ToArray();
            var tree         = new SearchTree <Problems.QueensPuzzle.State>(_problem.CreateState(initialState));
            var dfs          = new DepthFirstSearcher <Problems.QueensPuzzle.State, int>(
                tree,
                GetPossibleActions,
                ApplyAction,
                (x, a) => 1,
                x => x.IsSolution);


            var           updateCount  = 0;
            var           start        = DateTime.Now;
            Action <bool> updateCounts = (force) =>
            {
                if (!force && ++updateCount % 10000 > 0)
                {
                    return;
                }
                NodesGeneratedLabel.Text = "Generated = " + dfs.NodesGeneratedCount + " ";
                ExpandedNodesLabel.Text  = "Expanded = " + dfs.NodesExpandedCount + " ";
                RetainedNodesLabel.Text  = "Retained = " + dfs.NodesRetainedCount + " ";
                SecondsLabel.Text        = DateTime.Now.Subtract(start).TotalSeconds.ToString();
                _currentState            = dfs.CurrentNode.Data;
                panel1.Invalidate();
                Application.DoEvents();
            };

            dfs.NodeExpanded  += (s, a) => updateCounts(false);
            dfs.NodeGenerated += (s, a) => updateCounts(false);

            var solution = dfs.Search();

            updateCounts(true);
        }
예제 #15
0
        public override void Work()
        {
            //获取求解设置
            decimal terminalFactor = _ctx.GetParameter("TerminalFactor", 0.001m);
            int     iteration      = _ctx.GetParameter("Iteration", 10);
            int     resolution     = _ctx.GetParameter("Resolution", 60);
            decimal initMultipler  = _ctx.GetParameter("InitMultiper", 0.1m);

            string objectiveType = _ctx.GetParameter("ObjectiveType", "");

            // 相对-绝对时间转化器
            DiscreteTimeAdapter adapter
                = new DiscreteTimeAdapter(_ctx.StartTime, _ctx.EndTime, resolution);

            // 路径集
            Dictionary <CustomerArrival, List <TravelPath> > pathDict
                = new Dictionary <CustomerArrival, List <TravelPath> >();

            #region 建立初始网络,搜索可行路径
            //目标函数网络
            var objgraph = ObjectNetworkFactory.Create(objectiveType, _ctx, adapter); //new ObjectTravelHyperNetwork(_ctx, adapter);
            objgraph.Build();

            //基础网络
            var basicGraph = new BasicTravelHyperNetwork(_ctx, adapter);
            basicGraph.Build();

            SubTasks.Clear();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                Task ta = factory.StartNew(() =>
                {
                    var ori   = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                    var des   = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).DesSta;
                    var paths = DepthFirstSearcher.FindAllPaths(basicGraph,
                                                                new TravelHyperNode()
                    {
                        Time = adapter.ConvertToDiscreteTime(customer.ArriveTime), Station = ori, Price = 0
                    },
                                                                new TravelHyperNode()
                    {
                        Time = adapter.Horizon + 1440, Station = des, Price = 0
                    });
                    pathDict.Add(customer, new List <TravelPath>());
                    foreach (var path in paths)
                    {
                        pathDict[customer].Add(new TravelPath(basicGraph, path));
                    }
                });
                SubTasks.Add(ta);
            }
            Task.WaitAll(SubTasks.ToArray());
            #endregion

            #region 构建对偶问题 with CPLEX
            Cplex model = new Cplex();
            model.SetOut(null);
            INumVar theta = model.NumVar(double.MinValue, double.MaxValue); //θ

            model.AddMaximize(theta);

            Dictionary <IServiceSegment, INumVar> dual_rho = _ctx.Wor.RailwayTimeTable.Trains
                                                             .SelectMany(i => i.ServiceSegments).ToDictionary(i => i, i =>
                                                                                                              model.NumVar(0, double.MaxValue));

            Dictionary <CustomerArrival, Dictionary <TravelPath, INumVar> > dual_mu =
                new Dictionary <CustomerArrival, Dictionary <TravelPath, INumVar> >();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                dual_mu.Add(customer, new Dictionary <TravelPath, INumVar>());
                foreach (var path in pathDict[customer])
                {
                    dual_mu[customer].Add(path, model.NumVar(0, double.MaxValue));
                }
            }

            Dictionary <IEdge <TravelHyperNode>, INumVar> dual_lambda =
                new Dictionary <IEdge <TravelHyperNode>, INumVar>();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                foreach (var path in pathDict[customer])
                {
                    if (!dual_lambda.ContainsKey(path.ReservationArc))
                    {
                        dual_lambda.Add(path.ReservationArc, model.NumVar(0, double.MaxValue));
                    }
                }
            }
            #endregion

            #region 变量与乘子
            //决策变量 x
            Dictionary <CustomerArrival, TravelPath> x
                = new Dictionary <CustomerArrival, TravelPath>();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                x.Add(customer, new TravelPath());
            }

            //决策变量 w
            Dictionary <ITrainTrip, Dictionary <IRailwayStation, PricePath> > w
                = new Dictionary <ITrainTrip, Dictionary <IRailwayStation, PricePath> >();
            foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)
            {
                w.Add(train, new Dictionary <IRailwayStation, PricePath>());
                foreach (var sta in _ctx.Wor.Net.StationCollection)
                {
                    w[train].Add(sta, null);
                }
            }

            //辅助变量 y
            //记录每条弧在当前w的取值下是否可行(available),值为true = 可行;false = 不可行
            //超出了y记录的reservation arc 不会有人走
            Dictionary <IEdge <TravelHyperNode>, bool> y
                = new Dictionary <IEdge <TravelHyperNode>, bool>();
            foreach (var p in pathDict.Values.SelectMany(i => i))
            {
                if (p.ReservationArc != null && !y.ContainsKey(p.ReservationArc))
                {
                    y.Add(p.ReservationArc, false);
                }
            }

            //拉格朗日乘子 rho
            Dictionary <IServiceSegment, decimal> LM_rho = _ctx.Wor.RailwayTimeTable.Trains
                                                           .SelectMany(i => i.ServiceSegments).ToDictionary(i => i, i => initMultipler);

            //拉格朗日乘子 rho 迭代方向
            Dictionary <IServiceSegment, decimal> Grad_rho = _ctx.Wor.RailwayTimeTable.Trains
                                                             .SelectMany(i => i.ServiceSegments).ToDictionary(i => i, i => initMultipler);


            //拉格朗日乘子 mu
            Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> > LM_mu
                = new Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> >();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                LM_mu.Add(customer, new Dictionary <TravelPath, decimal>());
                foreach (var path in pathDict[customer])
                {
                    LM_mu[customer].Add(path, initMultipler);
                }
            }
            //拉格朗日乘子 mu 迭代方向
            Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> > Grad_mu
                = new Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> >();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                Grad_mu.Add(customer, new Dictionary <TravelPath, decimal>());
                foreach (var path in pathDict[customer])
                {
                    Grad_mu[customer].Add(path, initMultipler);
                }
            }

            //拉格朗日乘子 lambda
            Dictionary <IEdge <TravelHyperNode>, decimal> LM_lambda = new Dictionary <IEdge <TravelHyperNode>, decimal>();
            //WARNING: 这里缺少了没有旅客选择的reservation arc
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                foreach (var path in pathDict[customer])
                {
                    if (!LM_lambda.ContainsKey(path.ReservationArc))
                    {
                        LM_lambda.Add(path.ReservationArc, initMultipler);
                    }
                }
            }

            //拉格朗日乘子 lambda 迭代方向
            Dictionary <IEdge <TravelHyperNode>, decimal> Grad_lambda = new Dictionary <IEdge <TravelHyperNode>, decimal>();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                foreach (var path in pathDict[customer])
                {
                    if (!Grad_lambda.ContainsKey(path.ReservationArc))
                    {
                        Grad_lambda.Add(path.ReservationArc, initMultipler);
                    }
                }
            }

            #endregion

            decimal bigM1      = pathDict.Max(i => i.Value.Max(j => basicGraph.GetPathCost(j)));
            decimal bigM2      = _ctx.Pal.Count();
            decimal bigM       = Math.Max(bigM1, bigM2);
            decimal lowerBound = decimal.MinValue;
            decimal upperBound = decimal.MaxValue;
            bool    flag       = false;//对偶问题有解

            PrintIterationInfo($"Iteration Number, Lower Bound, Upper Bound, Best Lower Bound, Best Upper Bound, Total Gap(%) ");

            for (int iter = 0; iter < iteration; iter++)
            {
                Log($"--------------第{iter}轮求解开始--------------");

                bool hasFeasibleSolution = true;

                #region 求解LR问题
                SubTasks.Clear();
                foreach (CustomerArrival customer in _ctx.Pal)// 求解x
                {
                    Task ta = factory.StartNew(() =>
                    {
                        var graph = new LRxTravelHyperNetwork(_ctx, adapter, objgraph, customer, pathDict, LM_rho, LM_mu, LM_lambda);
                        graph.Build();
                        var ori = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                        var des = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).DesSta;
                        DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode> dijkstra
                            = new DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode>(graph, new TravelHyperNode()
                        {
                            Time    = adapter.ConvertToDiscreteTime(customer.ArriveTime),
                            Station = ori,
                            Price   = 0
                        });    //考虑该旅客到达时间
                        x[customer] = new TravelPath(graph, dijkstra.ShortestPathTo(
                                                         new TravelHyperNode()
                        {
                            Time    = adapter.Horizon + 1440,
                            Station = des,
                            Price   = 0
                        }));
                    });
                    SubTasks.Add(ta);
                }
                foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)
                {
                    foreach (IRailwayStation station in _ctx.Wor.Net.StationCollection)// 求解w
                    {
                        Task ta = factory.StartNew(() =>
                        {
                            var graph = DpnAlgorithm.BuildLRwGraph(_ctx, adapter, train, station, pathDict, basicGraph.LinkTrainDict, LM_mu, LM_lambda);
                            DijkstraShortestPaths <DirectedWeightedSparseGraph <string>, string> dijkstra
                                         = new DijkstraShortestPaths <DirectedWeightedSparseGraph <string>, string>(graph, "Start");//考虑该旅客到达时间
                            var nodepath = dijkstra.ShortestPathTo("End");
                            if (nodepath == null)
                            {
                                throw new System.Exception("No path found");
                            }
                            else
                            {
                                w[train][station] = new PricePath(graph, nodepath);
                            }
                        });
                        SubTasks.Add(ta);
                    }
                }
                Task.WaitAll(SubTasks.ToArray());

                foreach (var edge in y.Keys.ToArray())//更新y
                {
                    var sta   = edge.Source.Station;
                    var train = basicGraph.GetTrainByReservationLink(edge);
                    y[edge] = w[train][sta].GetWrapPoints(edge.Destination.Price, edge.Source.Time).Any();
                }
                #endregion

                #region 计算拉格朗日函数值作为下界

                decimal templowerBound       = 0m;
                decimal templowerBound_part1 = 0m;
                decimal templowerBound_part2 = 0m;
                decimal templowerBound_part3 = 0m;
                decimal templowerBound_part4 = 0m;
                Dictionary <CustomerArrival, decimal> lbValueDic
                    = new Dictionary <CustomerArrival, decimal>();
                //1 计算在基础网络中的路径cost
                foreach (CustomerArrival customer in _ctx.Pal)
                {
                    lbValueDic.Add(customer, objgraph.GetPathCost(x[customer]));
                    templowerBound_part1 += lbValueDic[customer];
                }

                //2计算BRUE项
                templowerBound_part2 += _ctx.Pal.Sum(c => pathDict[c].Sum(p =>
                {
                    decimal secondItem = 0m;
                    secondItem        += basicGraph.GetPathCost(x[c]) - basicGraph.GetPathCost(p) - _ctx.SitaDic[c.Customer.MarSegID];
                    secondItem        -= (p.ReservationArc != null && y[p.ReservationArc]) ? 0 : bigM;
                    return(secondItem * LM_mu[c][p]);
                }));

                //3计算In-train Capacity项
                Dictionary <IServiceSegment, int> ServiceDic = _ctx.Wor.RailwayTimeTable
                                                               .Trains.SelectMany(i => i.ServiceSegments)
                                                               .ToDictionary(i => i, i => 0);//当前service segment使用情况

                foreach (var p in x.Values)
                {
                    foreach (IServiceSegment seg in p.GetSegments(basicGraph))
                    {
                        ServiceDic[seg] += 1;
                    }
                }
                foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)
                {
                    foreach (var seg in train.ServiceSegments)
                    {
                        templowerBound_part3 += LM_rho[seg] * (ServiceDic[seg] - train.Carriage.Chairs.Count());
                    }
                }

                //4 计算reservation constraint 项
                Dictionary <IEdge <TravelHyperNode>, int> reservationDic
                    = new Dictionary <IEdge <TravelHyperNode>, int>();
                foreach (var p in x.Values)
                {
                    if (reservationDic.ContainsKey(p.ReservationArc))
                    {
                        reservationDic[p.ReservationArc] += 1;
                    }
                    else
                    {
                        reservationDic.Add(p.ReservationArc, 1);
                    }
                }
                foreach (var pair in y.Keys)
                {
                    //y是所有的reservation 的集合 reservationDic 是已经使用的reservation 集合
                    var res = reservationDic.Keys.FirstOrDefault(i => i.Source == pair.Source && i.Destination == pair.Destination);
                    templowerBound_part4 += LM_lambda[pair] * ((res != null ? reservationDic[res] : 0) - (y[pair] ? bigM : 0));
                }

                templowerBound = templowerBound_part1 + templowerBound_part2 + templowerBound_part3 + templowerBound_part4;

                //Log($"Lower Bound = { Math.Round(templowerBound, 2)}," +
                //   $"({ Math.Round(templowerBound_part1, 2) }" +
                //   $"+{ Math.Round(templowerBound_part2, 2)}" +
                //   $"+{ Math.Round(templowerBound_part3, 2)}" +
                //   $"+{ Math.Round(templowerBound_part4, 2)})");

                PrintLBSolution(DpnAlgorithm.GetTravelPathString(_ctx, adapter, objgraph, x, lbValueDic));
                #endregion

                #region 更新乘子
                if (flag)
                {
                    decimal LagLowerBound = Convert.ToDecimal(model.GetValue(theta));
                    Log($"LagLower Bound = { LagLowerBound }");
                    Log($"Lower Bound = { templowerBound }");
                    lowerBound = Math.Max(lowerBound, templowerBound);

                    decimal lagGap = LagLowerBound - templowerBound;

                    if (lagGap <= 0)//判断拉格朗日对偶问题是否达到最优
                    {
                        Log($"求解终止:对偶函数已最优。");
                        break;
                    }
                    else
                    {
                        /* 更新乘子值 */
                        foreach (var pair in dual_rho)
                        {
                            LM_rho[pair.Key] = Convert.ToDecimal(model.GetValue(pair.Value));
                        }
                        foreach (var pair in dual_lambda)
                        {
                            LM_lambda[pair.Key] = Convert.ToDecimal(model.GetValue(pair.Value));
                        }
                        foreach (CustomerArrival customer in _ctx.Pal)
                        {
                            foreach (var path in pathDict[customer])
                            {
                                LM_mu[customer][path] = Convert.ToDecimal(model.GetValue(dual_mu[customer][path]));
                            }
                        }
                    }
                }
                else /* 如果对偶问题无可行解,通过次梯度的方式更新乘子 */
                {
                    //decimal step = 1.618m / (iter + 1);
                    //foreach (CustomerArrival c in _ctx.Pal)//更新mu
                    //{
                    //    foreach (TravelPath p in pathDict[c])
                    //    {
                    //        Grad_mu[c][p] = basicGraph.GetPathCost(x[c]) - basicGraph.GetPathCost(p) - _ctx.SitaDic[c.Customer.MarSegID]
                    //            - ((p.ReservationArc != null && y[p.ReservationArc]) ? 0 : bigM);
                    //        LM_mu[c][p] = Math.Max(0, LM_mu[c][p] + step * Grad_mu[c][p]);
                    //    }
                    //}
                    //foreach (var pair in y.Keys) //更新lambda
                    //{
                    //    var res = reservationDic.Keys.FirstOrDefault(i => i.Source == pair.Source && i.Destination == pair.Destination);
                    //    Grad_lambda[pair] = ((res != null ? reservationDic[res] : 0) - (y[pair] ? bigM : 0));
                    //    LM_lambda[pair] = Math.Max(0, LM_lambda[pair] + step * Grad_lambda[pair]);
                    //}
                    //foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)//更新rho
                    //{
                    //    foreach (var seg in train.ServiceSegments)
                    //    {
                    //        Grad_rho[seg] = ServiceDic[seg] - train.Carriage.Chairs.Count();
                    //        LM_rho[seg] = Math.Max(0, LM_rho[seg] + step * Grad_rho[seg]);
                    //    }
                    //}
                }

                #endregion

                #region 求解拉格朗日对偶问题

                /* 求解 几何乘子 */
                // 增加 一个约束
                INumExpr exp = model.NumExpr();

                //2 计算BRUE项
                foreach (var c in _ctx.Pal)
                {
                    foreach (var p in pathDict[c])
                    {
                        decimal secondItem = 0m;
                        secondItem += basicGraph.GetPathCost(x[c]) - basicGraph.GetPathCost(p) - _ctx.SitaDic[c.Customer.MarSegID];
                        secondItem -= (p.ReservationArc != null && y[p.ReservationArc]) ? 0 : bigM;
                        exp         = model.Sum(exp, model.Prod(Convert.ToDouble(secondItem), dual_mu[c][p]));
                    }
                }

                //3计算In-train Capacity项 (这里直接用了计算下界时候的 Service_dic
                foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)
                {
                    foreach (var seg in train.ServiceSegments)
                    {
                        exp = model.Sum(exp, model.Prod(Convert.ToDouble(ServiceDic[seg]
                                                                         - train.Carriage.Chairs.Count()), dual_rho[seg]));
                    }
                }

                //4 计算reservation constraint 项 (这里直接用了计算下界时候的 reservationDic
                foreach (var pair in y.Keys)
                {
                    var res = reservationDic.Keys.FirstOrDefault(i => i.Source == pair.Source &&
                                                                 i.Destination == pair.Destination);
                    exp = model.Sum(exp, model.Prod(Convert.ToDouble(((res != null ? reservationDic[res] : 0)
                                                                      - (y[pair] ? bigM : 0))), dual_lambda[pair]));
                }

                model.AddGe(model.Sum(Convert.ToDouble(templowerBound_part1), exp), theta);

                /* Trust-Region */
                //var trExpr = model.Add()

                flag = model.Solve();
                Log($"Is Dual Problem Feasible: { flag }");

                #endregion

                #region 通过一个启发式规则计算上界(按照w模拟到达)

                var pathcost     = lbValueDic.ToDictionary(i => i.Key, i => i.Value);
                var x_least      = x.ToDictionary(i => i.Key, i => i.Value);//当前w下每个旅客的最短路径
                var x_upperbound = x.ToDictionary(i => i.Key, i => i.Value);
                var x_controlled = x.ToDictionary(i => i.Key, i => i.Value);

                #region 1-构建当前y下的最优x值
                SubTasks.Clear();
                foreach (CustomerArrival customer in _ctx.Pal)// 求解x
                {
                    Task ta = factory.StartNew(() =>
                    {
                        var controlledLRxgraph = new ControlledLRxTravelHyperNetwork(
                            _ctx, adapter, objgraph, customer, pathDict, LM_rho, LM_mu, LM_lambda, y);
                        controlledLRxgraph.Build();
                        var ori = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                        var des = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).DesSta;

                        TravelHyperNode startNode = new TravelHyperNode()
                        {
                            Time    = adapter.ConvertToDiscreteTime(customer.ArriveTime),
                            Station = ori,
                            Price   = 0
                        };
                        TravelHyperNode endNode = new TravelHyperNode()
                        {
                            Time    = adapter.Horizon + 1440,
                            Station = des,
                            Price   = 0
                        };

                        DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode> dijkstra
                            = new DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode>
                                  (controlledLRxgraph, startNode);//考虑该旅客到达时间

                        if (!dijkstra.HasPathTo(endNode))
                        {
                            throw new System.Exception("没有路径!");
                        }
                        else
                        {
                            x_controlled[customer] = new TravelPath(controlledLRxgraph, dijkstra.ShortestPathTo(endNode));
                        }
                    });
                    SubTasks.Add(ta);
                }
                Task.WaitAll(SubTasks.ToArray());
                #endregion

                # region 2-构建当前y下的出行最小值
                var solutiongraph = new ControlledTravelHyperNetwork(_ctx, adapter, y);
                solutiongraph.Build();
                Parallel.ForEach(_ctx.Pal, customer =>                //foreach (var customer in _ctx.Pal)//求此网络下每个旅客的最短路径
                {
                    var ori = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                    var des = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).DesSta;

                    TravelHyperNode startNode = new TravelHyperNode()
                    {
                        Time    = adapter.ConvertToDiscreteTime(customer.ArriveTime),
                        Station = ori,
                        Price   = 0
                    };

                    TravelHyperNode endNode = new TravelHyperNode()
                    {
                        Time    = adapter.Horizon + 1440,
                        Station = des,
                        Price   = 0
                    };

                    DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode> dijkstra
                        = new DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode>
                              (solutiongraph, startNode);

                    if (!dijkstra.HasPathTo(endNode))
                    {
                        throw new System.Exception("没有路径!");
                    }
                    else
                    {
                        x_least[customer] = new TravelPath(solutiongraph, dijkstra.ShortestPathTo(endNode));
                    }
                });
                #endregion

                #region 3-修复可行解
                var solutiongraphTemp = new SimNetwork(_ctx, adapter, y);//建立仿真网络
                solutiongraphTemp.Build();
                foreach (var customer in _ctx.Pal)
                {
                    x_upperbound[customer] = x_controlled[customer];
                    TravelPath path = x_controlled[customer];

                    if (!solutiongraphTemp.IsPathFeasible(path) ||
                        solutiongraphTemp.GetPathCost(path) > solutiongraph.GetPathCost(x_least[customer]) + _ctx.SitaDic[customer.Customer.MarSegID])//如果违反了容量约束或者BRUE约束
                    {
                        var ori = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                        var des = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).DesSta;
                        DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode> dijkstra
                            = new DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode>(solutiongraphTemp, new TravelHyperNode()
                        {
                            Time    = adapter.ConvertToDiscreteTime(customer.ArriveTime),
                            Station = ori,
                            Price   = 0
                        });

                        //重新查找路径,如果存在路径
                        if (dijkstra.HasPathTo(new TravelHyperNode()
                        {
                            Time = adapter.Horizon + 1440,
                            Station = des,
                            Price = 0
                        }))
                        {
                            x_upperbound[customer] = new TravelPath(solutiongraphTemp, dijkstra.ShortestPathTo(new TravelHyperNode()
                            {
                                Time    = adapter.Horizon + 1440,
                                Station = des,
                                Price   = 0
                            }));
                            if (solutiongraphTemp.GetPathCost(x_upperbound[customer]) <= //满足BRUE约束
                                solutiongraph.GetPathCost(x_least[customer]) + _ctx.SitaDic[customer.Customer.MarSegID])
                            {
                                path = x_upperbound[customer];
                            }
                            else
                            {
                                hasFeasibleSolution = false;
                                break;
                            }
                        }
                        else
                        {
                            hasFeasibleSolution = false;
                            break;
                        }
                    }

                    pathcost[customer] = objgraph.GetPathCost(path);

                    //加载路径
                    foreach (var seg in path.GetSegments(basicGraph))
                    {
                        solutiongraphTemp.AddUsage(seg, 1);
                    }
                }
                var tempUpperbound = _ctx.Pal.Sum(c => objgraph.GetPathCost(x_upperbound[c]));
                #endregion

                //如果有最优解再更新上界
                bool hasBetterUpperbound = tempUpperbound < upperBound;
                if (hasFeasibleSolution)
                {
                    upperBound = Math.Min(upperBound, tempUpperbound);
                }
                Log($"Upper Bound = {  Math.Round(tempUpperbound, 2) },找到可行解 : { hasFeasibleSolution.ToString()}");
                #endregion

                #region  Terminatation 判定
                Log($"Upper Bound = { tempUpperbound }");
                decimal absoluteGap = 0;
                string  gapStr      = "";
                //如果上限是无穷,那么此时gap也是无穷
                if (upperBound == decimal.MaxValue || lowerBound == decimal.MinValue)
                {
                    absoluteGap = decimal.MaxValue;
                    gapStr      = $"+∞";
                }
                else
                {
                    absoluteGap = upperBound - lowerBound;
                    gapStr      = $"{ Math.Round(absoluteGap, 2)}";
                }


                if (absoluteGap < terminalFactor && absoluteGap > 0)
                {
                    Log($"求解终止:Gap以满足终止条件,Gap={ absoluteGap }");
                    break;
                }

                Log($"Total Gap = { gapStr }");
                #endregion

                #region 输出信息

                //SendMessage($"#Iteration Number, Lower Bound, Upper Bound, Best Lower Bound, Best Upper Bound, Total Gap(%) ");
                PrintIterationInfo($"#{iter},{ Math.Round(templowerBound) },{ Math.Round(tempUpperbound) },{ Math.Round(lowerBound)}" +
                                   $",{ Math.Round(upperBound) },{ gapStr }");

                string ss = "###,";
                foreach (var s in LM_rho)
                {
                    ss += ($"{s.Key.ToString()}:{ s.Value.ToString() },");
                }
                PrintIterationInfo(ss);

                if (hasFeasibleSolution && hasBetterUpperbound)
                {
                    ObjValue = pathcost.Sum(i => i.Value);
                    PrintSolution(
                        DpnAlgorithm.GetTravelPathString(_ctx, adapter, solutiongraph, x_upperbound, pathcost),
                        DpnAlgorithm.GetPricingPathString(_ctx, adapter, w));
                }

                #endregion

                Log($"--------------第{iter}轮求解结束--------------");
            }
        private void IDNaiveButton_Click(object sender, EventArgs e)
        {
            var tree = new SearchTree<Problems.SlidingTilesPuzzle.State>(_currentState);
            var dfs = new DepthFirstSearcher<Problems.SlidingTilesPuzzle.State, int>(
                tree,
                x => x.GetActions(),
                (x, a) => x.Clone().ApplyAction(a),
                (x, a) => 1,
                x => x.IsSolution);
            var id = new IterativeDeepeningDepthFirstSearch<Problems.SlidingTilesPuzzle.State, int>(dfs);

            var updateCount = 0;
            var start = DateTime.Now;
            Action<bool> updateCounts = (force) =>
            {
                if (!force && ++updateCount % 10000 > 0) return;
                NodesGeneratedLabel.Text = "Generated = " + dfs.NodesGeneratedCount + " ";
                ExpandedNodesLabel.Text = "Expanded = " + dfs.NodesExpandedCount + " ";
                RetainedNodesLabel.Text = "Retained = " + dfs.NodesRetainedCount + " ";
                SecondsLabel.Text = DateTime.Now.Subtract(start).TotalSeconds.ToString() + " (next depth = " + dfs.NextCostThreshhold + ")";
                _currentState = dfs.CurrentNode.Data;
                panel1.Invalidate();
                Application.DoEvents();
            };

            dfs.NodeExpanded += (s, a) => updateCounts(false);
            dfs.NodeGenerated += (s, a) => updateCounts(false);

            var solution = id.Search();

            updateCounts(true);
        }
예제 #17
0
        private void button2_Click(object sender, EventArgs e)
        {
            var initialState = Enumerable.Range(0, _problem.Size).Select(x => -1).ToArray();
            var tree = new SearchTree<Problems.QueensPuzzle.State>(_problem.CreateState(initialState));
            var dfs = new DepthFirstSearcher<Problems.QueensPuzzle.State, int>(
                tree,
                GetPossibleActions,
                ApplyAction,
                (x, a) => 1,
                x => x.IsSolution);

            var updateCount = 0;
            var start = DateTime.Now;
            Action<bool> updateCounts = (force) =>
            {
                if (!force && ++updateCount % 10000 > 0) return;
                NodesGeneratedLabel.Text = "Generated = " + dfs.NodesGeneratedCount + " ";
                ExpandedNodesLabel.Text = "Expanded = " + dfs.NodesExpandedCount + " ";
                RetainedNodesLabel.Text = "Retained = " + dfs.NodesRetainedCount + " ";
                SecondsLabel.Text = DateTime.Now.Subtract(start).TotalSeconds.ToString();
                _currentState = dfs.CurrentNode.Data;
                panel1.Invalidate();
                Application.DoEvents();
            };

            dfs.NodeExpanded += (s,a) => updateCounts(false);
            dfs.NodeGenerated += (s, a) => updateCounts(false);

            var solution = dfs.Search();

            updateCounts(true);
        }
예제 #18
0
        public void LRwPathSearchTest()
        {
            DPNProblemContext   ctx     = GenerateProblemContext();
            DiscreteTimeAdapter adapter = new DiscreteTimeAdapter(ctx.StartTime, ctx.EndTime, 1);
            var travelgraph             = new BasicTravelHyperNetwork(ctx, adapter);

            travelgraph.Build();

            /* Train01 Station A*/
            var train   = ctx.Wor.RailwayTimeTable.Trains.First();
            var station = ctx.Wor.Net.StationCollection.First();

            //路径集
            Dictionary <CustomerArrival, List <TravelPath> > pathDict
                = new Dictionary <CustomerArrival, List <TravelPath> >();

            foreach (CustomerArrival c in ctx.Pal)
            {
                var ori   = (ctx.Wor.Mar[c.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                var des   = (ctx.Wor.Mar[c.Customer.MarSegID] as IRailwayMarketSegment).DesSta;
                var paths = DepthFirstSearcher.FindAllPaths(travelgraph,
                                                            new TravelHyperNode()
                {
                    Time = adapter.ConvertToDiscreteTime(c.ArriveTime), Station = ori, Price = 0
                },
                                                            new TravelHyperNode()
                {
                    Time = adapter.Horizon + 1440, Station = des, Price = 0
                });
                pathDict.Add(c, new List <TravelPath>());
                foreach (var path in paths)
                {
                    pathDict[c].Add(new TravelPath(travelgraph, path));
                }
            }

            //拉格朗日乘子 mu
            Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> > LM_mu
                = new Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> >();

            foreach (CustomerArrival customer in ctx.Pal)
            {
                LM_mu.Add(customer, new Dictionary <TravelPath, decimal>());
                foreach (var path in pathDict[customer])
                {
                    LM_mu[customer].Add(path, 2);
                }
            }

            // 拉格朗日乘子 lambda
            Dictionary <IEdge <TravelHyperNode>, decimal> LM_lambda = new Dictionary <IEdge <TravelHyperNode>, decimal>();

            foreach (CustomerArrival customer in ctx.Pal)
            {
                foreach (var path in pathDict[customer])
                {
                    if (!LM_lambda.ContainsKey(path.ReservationArc))
                    {
                        LM_lambda.Add(path.ReservationArc, 1);
                    }
                }
            }

            var graph = DpnAlgorithm.BuildLRwGraph(ctx, adapter, train, station,
                                                   pathDict,
                                                   travelgraph.LinkTrainDict,
                                                   LM_mu,
                                                   LM_lambda);

            DijkstraShortestPaths <DirectedWeightedSparseGraph <string>, string> dijkstra
                = new DijkstraShortestPaths <DirectedWeightedSparseGraph <string>, string>(graph,
                                                                                           "Start");

            Assert.IsTrue(dijkstra.HasPathTo("End") == true);

            var       pathToC   = string.Empty;
            var       pricepath = dijkstra.ShortestPathTo("End");
            PricePath p         = new PricePath(graph, pricepath);

            Assert.IsTrue(p.GetWrapPoints(0.9m, 2).Count() > 0);
            Assert.IsFalse(p.GetWrapPoints(1.1m, 2).Count() > 0);

            foreach (var node in pricepath)
            {
                pathToC = String.Format("{0}({1}) -> ", pathToC, node);
            }

            pathToC = pathToC.TrimEnd(new char[] { ' ', '-', '>' });
            Console.WriteLine("Shortest path to Station 'C': " + pathToC + "\r\n");
            Assert.AreEqual(23m, Math.Round(dijkstra.DistanceTo("End")));
        }
예제 #19
0
        public void BuildLRwTest()
        {
            DPNProblemContext   ctx     = GenerateProblemContext();
            DiscreteTimeAdapter adapter = new DiscreteTimeAdapter(ctx.StartTime, ctx.EndTime, 1);
            var travelgraph             = new BasicTravelHyperNetwork(ctx, adapter);

            travelgraph.Build();

            var train   = ctx.Wor.RailwayTimeTable.Trains.First();
            var station = ctx.Wor.Net.StationCollection.First();

            //路径集
            Dictionary <CustomerArrival, List <TravelPath> > pathDict
                = new Dictionary <CustomerArrival, List <TravelPath> >();

            foreach (CustomerArrival c in ctx.Pal)
            {
                var ori   = (ctx.Wor.Mar[c.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                var des   = (ctx.Wor.Mar[c.Customer.MarSegID] as IRailwayMarketSegment).DesSta;
                var paths = DepthFirstSearcher.FindAllPaths(travelgraph,
                                                            new TravelHyperNode()
                {
                    Time = adapter.ConvertToDiscreteTime(c.ArriveTime), Station = ori, Price = 0
                },
                                                            new TravelHyperNode()
                {
                    Time = adapter.Horizon + 1440, Station = des, Price = 0
                });
                pathDict.Add(c, new List <TravelPath>());
                foreach (var path in paths)
                {
                    pathDict[c].Add(new TravelPath(travelgraph, path));
                }
            }

            //拉格朗日乘子 mu
            Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> > LM_mu
                = new Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> >();

            foreach (CustomerArrival customer in ctx.Pal)
            {
                LM_mu.Add(customer, new Dictionary <TravelPath, decimal>());
                foreach (var path in pathDict[customer])
                {
                    LM_mu[customer].Add(path, 2);
                }
            }

            // 拉格朗日乘子 lambda
            Dictionary <IEdge <TravelHyperNode>, decimal> LM_lambda = new Dictionary <IEdge <TravelHyperNode>, decimal>();

            //WARNING: 这里缺少了没有旅客选择的reservation arc
            foreach (CustomerArrival customer in ctx.Pal)
            {
                foreach (var path in pathDict[customer])
                {
                    if (!LM_lambda.ContainsKey(path.ReservationArc))
                    {
                        LM_lambda.Add(path.ReservationArc, 1);
                    }
                }
            }

            var graph = DpnAlgorithm.BuildLRwGraph(ctx, adapter, train, station,
                                                   pathDict,
                                                   travelgraph.LinkTrainDict,
                                                   LM_mu,
                                                   LM_lambda);

            Assert.AreEqual(27, graph.EdgesCount);
        }
예제 #20
0
        public void DepthFirstSearchTest(Graph graph, string[] order)
        {
            // a --- b ----------f---------h
            //  -               -
            //   -           -
            //   -        -
            //   c------d-------e----------g
            "Given an undirected graph".x(() =>
            {
                graph = new Graph();

                var a = new GraphNode()
                {
                    name = "a"
                };
                var b = new GraphNode()
                {
                    name = "b"
                };
                var c = new GraphNode()
                {
                    name = "c"
                };
                var d = new GraphNode()
                {
                    name = "d"
                };
                var e = new GraphNode()
                {
                    name = "e"
                };
                var f = new GraphNode()
                {
                    name = "f"
                };
                var g = new GraphNode()
                {
                    name = "g"
                };
                var h = new GraphNode()
                {
                    name = "h"
                };

                a.children = new GraphNode[] { b, c };
                b.children = new GraphNode[] { a, f };
                c.children = new GraphNode[] { a, d };
                d.children = new GraphNode[] { e, c, f };
                e.children = new GraphNode[] { d, g };
                f.children = new GraphNode[] { h, b, d };
                g.children = new GraphNode[] { e };
                h.children = new GraphNode[] { f };

                graph.root = a;
            });

            "When I do a breadth first search".x(() =>
            {
                var searcher = new DepthFirstSearcher();
                order        = searcher.PrintOrder(graph);
            });

            "Then the print order is as expected".x(() =>
            {
                var expected = new[] { "a", "b", "f", "h", "d", "e", "g", "c" };
                Assert.Equal(expected, order);
            });
        }
        private void DfsButton_Click(object sender, EventArgs e)
        {
            // Without any I/D or heuristics this is the same as random search

            var tree = new SearchTree<Problems.SlidingTilesPuzzle.State>(_currentState);
            var dfs = new DepthFirstSearcher<Problems.SlidingTilesPuzzle.State, int>(
                tree,
                x => x.GetActions().RandomizeOrder(),
                (x, a) => x.ApplyAction(a), // Don't need to clone because DFS is one way
                (x, a) => 1,
                x => x.IsSolution);

            var updateCount = 0;
            var start = DateTime.Now;
            Action<bool> updateCounts = (force) =>
            {
                if (!force && ++updateCount % 10000 > 0) return;
                NodesGeneratedLabel.Text = "Generated = " + dfs.NodesGeneratedCount + " ";
                ExpandedNodesLabel.Text = "Expanded = " + dfs.NodesExpandedCount + " ";
                RetainedNodesLabel.Text = "Retained = " + dfs.NodesRetainedCount + " ";
                SecondsLabel.Text = DateTime.Now.Subtract(start).TotalSeconds.ToString();
                _currentState = dfs.CurrentNode.Data;
                panel1.Invalidate();
                Application.DoEvents();
            };

            dfs.NodeExpanded += (s,a) => updateCounts(false);
            dfs.NodeGenerated += (s, a) => updateCounts(false);

            var solution = dfs.Search();

            updateCounts(true);
        }