static void Main(string[] args)
        {
            string data_path = "Server = PC-201606172102\\SQLExpress;DataBase = 乘务计划;Integrated Security = true";
            //string data_path = "Server = PC-201606172102\\SQLExpress;DataBase = 乘务计划CSP1440;Integrated Security = true";
            NetWork Net = new NetWork();

            Net.CreateNetwork(data_path);
            Net.IsAllTripsCovered();
            //检查无误
            InitialSolution IS = new InitialSolution(Net);

            Stopwatch sw = new Stopwatch();

            sw.Start();

            IS.GetFeasibleSolutionByPenalty();
            //IS.GetFeasibleSolutionByMethod1();//顺逆向标号在多基地时有问题:如对点i,顺向时最短路对应基地为B1,逆向时最短路对应基地为B2.错误
            sw.Stop();

            Report Report_IS = new Report(IS.PathSet);

            Console.WriteLine(Report_IS.TransferSolution());

            Console.WriteLine("平均纯乘务时间:{0} 平均换乘时间{1} 平均task数{2}", Report_IS.summary_mean.mean_PureCrew
                              , Report_IS.summary_mean.mean_Trans, Report_IS.summary_mean.mean_Tasks);
            Report_IS.WriteCrewPaths(@"D:\代码项目\C#\CG-version2.1_cost_1440-重构\CG_CSP_1440\ISS_LineList.txt");

            Console.WriteLine(sw.Elapsed.TotalSeconds);
            //checked:OK
            /*********<<下面开始测试CG>>***************************************************************************/
            CSP csp = new CSP(Net);

            csp.Branch_and_Price(IS);
            int y = 0;
        }
        /// <summary>分支定价
        /// 从指定的初始解作为上界开始
        /// </summary>
        /// <param name="IS"></param>
        public void Branch_and_Price(InitialSolution IS)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            Build_RMP(IS);

            root_node = new TreeNode();
            CG(ref root_node);

            sw.Stop();
            Console.WriteLine("根节点求解时间: " + sw.Elapsed.TotalSeconds);

            best_feasible_solution = new List <int>();
            //RecordFeasibleSolution(root_node, ref best_feasible_solution);
            RecordFeasibleSolution(ref best_feasible_solution);
            double UB = IS.initial_ObjValue;//int.MaxValue;
            double LB = root_node.obj_value;

            sw.Restart();

            Branch_and_Bound(root_node, LB, UB);

            sw.Stop();
            Console.WriteLine("分支定价共花费时间:" + sw.Elapsed.TotalSeconds);
        }
        /// <summary>建立最初的RMP
        /// 依据初始解
        /// </summary>
        /// <param name="IS"></param>
        public void Build_RMP(InitialSolution IS)
        {
            initialPath_num    = IS.PathSet.Count;
            trip_num           = TripList.Count;
            realistic_trip_num = NetWork.num_Physical_trip;

            DvarSet  = new List <INumVar>();
            CoefSet  = new List <double>();
            A_Matrix = new List <int[]>();
            PathSet  = new List <Pairing>();

            //virtualVarSet = new List<INumVar>();
            //for (int virtual_x = 0; virtual_x < realistic_trip_num; virtual_x++) {
            //    virtualVarSet.Add(masterModel.NumVar(0, 1, NumVarType.Float));
            //}

            CoefSet  = IS.Coefs;
            A_Matrix = IS.A_Matrix;
            PathSet  = IS.PathSet;

            foreach (var p in PathSet)
            {
                ColumnPool.Add(p);
            }

            int i, j;

            Obj        = masterModel.AddMinimize();
            Constraint = new IRange[realistic_trip_num];
            /**按行建模**/
            //vars and obj function
            for (j = 0; j < initialPath_num; j++)
            {
                INumVar var = masterModel.NumVar(0, 1, NumVarType.Float);
                DvarSet.Add(var);
                Obj.Expr = masterModel.Sum(Obj.Expr, masterModel.Prod(CoefSet[j], DvarSet[j]));
            }
            //constraints
            for (i = 0; i < realistic_trip_num; i++)
            {
                INumExpr expr = masterModel.NumExpr();

                for (j = 0; j < initialPath_num; j++)
                {
                    expr = masterModel.Sum(expr,
                                           masterModel.Prod(A_Matrix[j][i], DvarSet[j]));//在从初始解传值给A_Matrix,已经针对网络复制作了处理
                }

                Constraint[i] = masterModel.AddGe(expr, 1);
            }
        }
        /// <summary>分支定价
        /// 从指定的初始解作为上界开始
        /// </summary>
        /// <param name="IS"></param>
        public void Branch_and_Price(InitialSolution IS) //initial solution初始解
        {
            Stopwatch sw = new Stopwatch();              //stopwatch获取以每秒计时周期数表示的计时器频率,即计时

            sw.Start();

            //Build_RMP(IS);
            Build_RMP_YY(IS); //20191004
            WriteModelToFIle();

            root_node = new TreeNode();
            CG(ref root_node);                                        //ref-引用,修改参数变量的修改也将导致原来变量的值被修改

            sw.Stop();
            Console.WriteLine("根节点求解时间: " + sw.Elapsed.TotalSeconds);
            Console.WriteLine("根节点目标值: " + root_node.obj_value);

            best_feasible_solution = new List <int>();                //最优解
            //RecordFeasibleSolution(root_node, ref best_feasible_solution);
            RecordFeasibleSolution(ref best_feasible_solution);
            double UB = IS.initial_ObjValue;//int.MaxValue;
            double LB = root_node.obj_value;

            sw.Restart();

            //Branch_and_Bound(root_node , LB , UB);
            // 不分支定界了,转化为整数规划求解
            IConversion mip = masterModel.Conversion(DvarSet.ToArray(), NumVarType.Int);

            masterModel.Add(mip);
            masterModel.Solve();
            Console.WriteLine("RMP_BOJ:" + masterModel.GetObjValue());
            RecordFeasibleSolution(ref best_feasible_solution);
            WriteOptScheduleToFile();

            sw.Stop();
            Console.WriteLine("分支定价共花费时间:" + sw.Elapsed.TotalSeconds);
        }
Exemple #5
0
        public void TestInstance(string caseName, string mealWindow, DataReader Data, ref Summary singleCaseSummary)
        {
            Stopwatch sw_all       = new Stopwatch();
            Stopwatch sw_creat_net = new Stopwatch();
            Stopwatch sw_IS        = new Stopwatch();
            Stopwatch sw_BandB     = new Stopwatch();

            sw_all.Start();
            sw_creat_net.Start();
            sw_IS.Start();

            NetWork Net = new NetWork();

            Net.CreateNetwork(Data);
            Net.IsAllTripsCovered();
            sw_creat_net.Stop();

            Console.WriteLine("connect arc num: {0}", Net.ArcSet.Count);
            Console.WriteLine("connect node num: {0}", Net.NodeSet.Count);

            //get initail solution
            InitialSolution IS = new InitialSolution(Net);

            //IS.GetFeasibleSolutionByPenalty();
            //IS.GetFeasibleSolutionByMethod1();
            IS.GetVirtualPathSetAsInitSoln();
            sw_IS.Stop();
            //Report Report_IS = new Report(IS.PathSet);
            //Console.WriteLine(Report_IS.TransferSolution());
            //Console.WriteLine("平均纯乘务时间:{0} 平均换乘时间{1} 平均task数{2}", Report_IS.summary_mean.mean_PureCrew,
            //    Report_IS.summary_mean.mean_Trans, Report_IS.summary_mean.mean_Tasks);

            //string initial_solution_dir = System.Environment.CurrentDirectory + "\\结果\\" + caseName + "\\初始解.txt";
            //Report_IS.WriteCrewPaths(initial_solution_dir);
            //Console.WriteLine(sw_IS.Elapsed.TotalSeconds);

            /*********<<下面开始测试CG>>***************************************************************************/
            sw_BandB.Start();
            CSP csp = new CSP(Net);

            csp.testCase = caseName + "\\" + mealWindow;
            csp.Branch_and_Price(IS);
            sw_BandB.Stop();
            sw_all.Stop();

            Logger.GetUncoveredTasks(csp.GetOptPathSet(), Net.TripList, caseName, mealWindow);
            Logger.GetSchedule(csp.GetOptPathSet(), caseName, mealWindow);


            singleCaseSummary = new Summary("CG", caseName + "_" + mealWindow, sw_all.Elapsed.TotalSeconds, csp.LB_LR, csp.UB_LR, csp.num_all_crew);

            string       path     = System.Environment.CurrentDirectory + "\\结果\\" + caseName + "\\" + mealWindow + "\\求解信息.txt";
            FileStream   fs       = new FileStream(path, FileMode.Create);
            StreamWriter strwrite = new StreamWriter(fs);

            strwrite.WriteLine("建网时间:{0}", sw_creat_net.Elapsed.TotalSeconds);
            strwrite.WriteLine("接续弧的数量:{0}", Net.ArcSet.Count());
            strwrite.WriteLine("网络中节点数量:{0}", Net.NodeSet.Count());
            //strwrite.WriteLine("初始解产生时间:{0}", sw_IS.Elapsed.TotalSeconds);
            strwrite.WriteLine("LP_OPT_SOLN时间:{0}", csp.time_root_node);
            strwrite.WriteLine("分支定界用时:{0}", sw_BandB.Elapsed.TotalSeconds);
            strwrite.WriteLine("总乘务组数量:{0}", csp.num_all_crew);
            strwrite.WriteLine("模型总共求解时间:{0}", sw_all.Elapsed.TotalSeconds);
            strwrite.WriteLine("总目标函数:{0}", /*csp.OBJVALUE);*/ csp.All_obj);
            strwrite.WriteLine("最短路总计算次数:{0}", csp.total_nums_rcspp);
            strwrite.WriteLine("初始解列数:{0}", IS.PathSet.Count);
            strwrite.WriteLine("列池总数:{0}", csp.ColumnPool.Count);
            strwrite.Close();
            fs.Close();

            // get objective value in the process of iterations
            StreamWriter obj_iter = new StreamWriter(System.Environment.CurrentDirectory + "\\结果\\" + caseName + "\\" + mealWindow + "\\OBJ迭代.csv");

            obj_iter.WriteLine("ObjValue");
            foreach (var obj in csp.obj_iter)
            {
                obj_iter.WriteLine(obj);
            }
            obj_iter.Close();

            //string num_label_iter = System.Environment.CurrentDirectory + "\\结果\\" + caseName + "\\标号数量与求解时间迭代(2).csv";
            //strwrite = new StreamWriter(num_label_iter, false, Encoding.Default);
            //strwrite.WriteLine("iter,label num,time*10000");
            //for (int i = 0; i < csp.num_label_iter.Count; i++)
            //{
            //    strwrite.WriteLine(i + 1 + "," + csp.num_label_iter[i] + "," + csp.time_rcspp[i] * 10000);
            //}
            //strwrite.Close();
        }
        /// <summary>分支定价
        /// 从指定的初始解作为上界开始
        /// </summary>
        /// <param name="IS"></param>
        public void Branch_and_Price(InitialSolution IS)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            Build_RMP(IS);

            root_node = new TreeNode();
            CG(ref root_node);

            sw.Stop();
            time_root_node = sw.Elapsed.TotalSeconds;
            Console.WriteLine("根节点求解时间: " + sw.Elapsed.TotalSeconds);

            best_feasible_solution = new List <int>();
            //RecordFeasibleSolution(root_node, ref best_feasible_solution);
            RecordFeasibleSolution(ref best_feasible_solution);
            double UB = IS.initial_ObjValue;//int.MaxValue;
            double LB = root_node.obj_value;

            sw.Restart();

            Branch_and_Bound(root_node, LB, UB);

            #region 转为mip

            /*
             * foreach (var x in DvarSet) {
             *  x.LB = 0;
             *  x.UB = 1;
             * }
             *
             * IConversion mip = masterModel.Conversion(DvarSet.ToArray(), NumVarType.Int);
             * masterModel.Add(mip);
             * masterModel.Solve();
             * Console.WriteLine("**************MIP_OBJ: {0}**************", masterModel.GetObjValue());
             * RecordFeasibleSolution(ref best_feasible_solution);
             * string path = System.Environment.CurrentDirectory + "\\结果\\" + testCase;
             * StreamWriter feasible_solutions = new StreamWriter(path + "\\mipSoln.csv", false, Encoding.Default);
             * Report repo = new Report();
             * int num = 1;
             * int start_cost = 1;
             * double sum_start_cost = 0;
             * double sum_accumuworktime = 0;
             *
             * List<Pairing> optSoln = new List<Pairing>();
             * for(int i = 0; i < DvarSet.Count; i++) {
             *  var x = DvarSet[i];
             *  if (masterModel.GetValue(x) > 0) {
             *
             *      feasible_solutions.WriteLine("乘务交路 " + (num++) + " ");
             *      StringBuilder singlepath = new StringBuilder();
             *      repo.summary_single.SetValue(0, 0, 0, 0);
             *      feasible_solutions.Write(repo.translate_single_pairing(ColumnPool[i],
             *                              ref singlepath, ref repo.summary_single));
             *      feasible_solutions.WriteLine();
             *      sum_accumuworktime += repo.summary_single.accumuwork;
             *      sum_start_cost += start_cost++;
             *
             *      optSoln.Add(ColumnPool[i]);
             *  }
             * }
             * feasible_solutions.Close();
             *
             * //masterModel.WriteSolution(testCase + "\\_mip.sln");
             * //masterModel.ExportModel(testCase + "\\_mip.LP");
             *
             * num_all_crew = --num;
             * Console.WriteLine("num_all_crew " + num_all_crew);
             * //Console.WriteLine("ALL_obj" + All_obj);
             * All_obj = 1440 * num;
             * All_obj += sum_accumuworktime +  Get_Stop_cost(num);//+ sum_start_cost;
             * Console.WriteLine("sum_start_cost = {0}\nsum_stop_cost = {1}", sum_start_cost, Get_Stop_cost(num));
             */
            #endregion


            Console.WriteLine("num_all_crew:" + num_all_crew);
            Console.WriteLine("ALL_obj:" + All_obj);

            sw.Stop();
            Console.WriteLine("分支定界共花费时间:" + sw.Elapsed.TotalSeconds);
        }
        public void Build_RMP_YY(InitialSolution IS)//主问题的建模
        {
            initialPath_num    = IS.PathSet.Count;
            trip_num           = TripList.Count;
            realistic_trip_num = NetWork.num_Physical_trip;

            A_Matrix   = IS.A_Matrix;
            DvarSet    = new List <INumVar>(); //x
            CoefSet    = new List <double>();  //cij
            ObjCoefSet = new List <double>();
            PathSet    = new List <Pairing>(); //列池

            CoefSet = IS.Coefs;                //IS初始解
            PathSet = IS.PathSet;

            ObjCoefSet = IS.ObjCoefs;

            foreach (var p in PathSet)
            {
                ColumnPool.Add(p);
            }

            masterModel = new Cplex();
            Obj         = masterModel.AddMinimize();
            //Constraint = new IRange[realistic_trip_num];
            Ct_cover   = new IRange[NUMBER_CREW];
            Ct_crewNum = new IRange[5][]; //默认每条交路为5天
            ct_nb      = new List <IRange>();

            /**按行建模**/
            //vars and obj function
            int i, j;

            for (j = 0; j < initialPath_num; j++)                          //定义决策变量和目标函数
            {
                INumVar dvar = masterModel.NumVar(0, 1, NumVarType.Float); //INumVar-cplex里面的,定义决策变量。后面括号中的意思是定义var是0-1之间的浮点值
                dvar.Name = "crew_" + PathSet[j].Arcs.First().D_Point.CrewID + "_" + j;

                DvarSet.Add(dvar);
                Obj.Expr = masterModel.Sum(Obj.Expr, masterModel.Prod(CoefSet[j], DvarSet[j]));//后面的小括号里面是一个cij*xj,大括号里面的是累计,包括之前的expr
            }

            /*constraints*/

            //ct:每条交路每条担当的人数满足要求
            #region //该条约束不需要,因为输入已经决定了,只要有可行解,该条约束必然满足

            /*for (i = 0; i < 5; i++)//对每一天
             * {
             *  INumExpr expr = masterModel.NumExpr();
             *  Dictionary<int, List<int>> route_paths_map = new Dictionary<int, List<int>>();
             *  for (j = 0; j < initialPath_num; j++) //对每天的工作链分类
             *  {
             *      if (A_Matrix[j][i] == 0) {
             *          continue;
             *      }
             *      if (!route_paths_map.ContainsKey(A_Matrix[j][i])) {
             *          route_paths_map.Add(A_Matrix[j][i], new List<int>());
             *      }
             *      route_paths_map[A_Matrix[j][i]].Add(j);
             *  }
             *
             *  Ct_crewNum[i] = new IRange[route_paths_map.Count];
             *  foreach (var routePathsPair in route_paths_map) { //对第i天的每条交路
             *      foreach (var xj in routePathsPair.Value)
             *      {
             *          expr = masterModel.Sum(expr, DvarSet[xj]);
             *      }
             *
             *      Ct_crewNum[i][routePathsPair.Key-1] = masterModel.AddGe(expr, 1); //20191004 一条交路1个人 TODO
             *      string name = "day_" + i + "_route_" + routePathsPair.Key;
             *      Ct_crewNum[i][routePathsPair.Key-1].Name = name;
             *
             *      ct_nb.Add(Ct_crewNum[i][routePathsPair.Key - 1]);
             *  }
             * }
             */
            #endregion

            // ct:每个乘务员只能有一条工作链
            Dictionary <int, List <int> > crewID_paths_map = new Dictionary <int, List <int> >();
            for (j = 0; j < initialPath_num; j++)
            {
                Pairing path    = PathSet[j];
                int     crew_id = path.crewID;
                if (!crewID_paths_map.ContainsKey(crew_id))
                {
                    crewID_paths_map.Add(crew_id, new List <int>());
                }
                crewID_paths_map[crew_id].Add(j);
            }
            if (crewID_paths_map.Count != NUMBER_CREW)
            {
                throw new System.Exception("乘务员数量有误");
            }

            foreach (var crewID_paths_pair in crewID_paths_map)
            {
                INumExpr expr = masterModel.NumExpr();
                foreach (var xj in crewID_paths_pair.Value)
                {
                    expr = masterModel.Sum(expr, DvarSet[xj]);
                }
                Ct_cover[crewID_paths_pair.Key - 1] = masterModel.AddEq(expr, 1);
            }
        }
        /// <summary>建立最初的RMP
        /// 依据初始解
        /// </summary>
        /// <param name="IS"></param>
        public void Build_RMP(InitialSolution IS)//主问题的建模
        {
            initialPath_num    = IS.PathSet.Count;
            trip_num           = TripList.Count;
            realistic_trip_num = NetWork.num_Physical_trip;

            DvarSet       = new List <INumVar>(); //x
            CoefSet       = new List <double>();  //cij
            AccumuWorkSet = new List <double>();  //每条交路累计工作时间
            ObjCoefSet    = new List <double>();
            A_Matrix      = new List <int[]>();   //aij
            PathSet       = new List <Pairing>(); //列池
            //int n = 196;//n代表的是整个高一车队每天所需要的乘务员和乘务长的总和


            CoefSet       = IS.Coefs;//IS初始解
            AccumuWorkSet = IS.AccumuWorkSet;
            A_Matrix      = IS.A_Matrix;
            PathSet       = IS.PathSet;
            ObjCoefSet    = IS.ObjCoefs;

            //for(int k = 0 ; k < IS.Coefs.Count ; k++)
            //{
            //    ObjCoefSet.Add(Network.GetObjCoef(IS.AccumuWorkSet[k] , IS.Coefs[k]));
            //}

            foreach (var p in PathSet)
            {
                ColumnPool.Add(p);
            }

            int i, j;

            masterModel = new Cplex();
            Obj         = masterModel.AddMinimize();
            Constraint  = new IRange[realistic_trip_num];//这种I打头的都是cplex里面的东西
            /**按行建模**/
            //vars and obj function
            for (j = 0; j < initialPath_num; j++)                                               //定义决策变量和目标函数
            {
                INumVar var = masterModel.NumVar(0, 1, NumVarType.Float);                       //INumVar-cplex里面的,定义决策变量。后面括号中的意思是定义var是0-1之间的浮点值
                DvarSet.Add(var);
                Obj.Expr = masterModel.Sum(Obj.Expr, masterModel.Prod(CoefSet[j], DvarSet[j])); //后面的小括号里面是一个cij*xj,大括号里面的是累计,包括之前的expr
            }
            //constraints
            for (i = 0; i < realistic_trip_num; i++) //对每一行    这部分的内容是aij*xj>=n
            {
                INumExpr expr = masterModel.NumExpr();

                for (j = 0; j < initialPath_num; j++) //对每一列
                {
                    expr = masterModel.Sum(expr,
                                           masterModel.Prod(A_Matrix[j][i], DvarSet[j])); //在从初始解传值给A_Matrix,已经针对网络复制作了处理
                }//小括号路里aij*xj

                Constraint[i] = masterModel.AddGe(expr, NUMBER_CREW); //约束list addge表示返回一个大于等于n的数
            }

            for (j = 0; j < initialPath_num; j++)//对每一列
            {
                INumExpr expr = masterModel.NumExpr();
                expr = masterModel.Sum(expr, DvarSet[j]);//在从初始解传值给A_Matrix,已经针对网络复制作了处理
            }


            //这里怎样使约束expr的值等于1????????????????????????????????????????????????
        }
        static void Main(string[] args)
        {
            //string data_path = "Server = PC-201606172102\\SQLExpress;DataBase = 乘务计划;Integrated Security = true";
            //string data_path = "Server = PC-201606172102\\SQLExpress;DataBase = 乘务计划CSP1440;Integrated Security = true";
            // string data_dir = @"\data\京津";
            Stopwatch sw_all       = new Stopwatch();
            Stopwatch sw_creat_net = new Stopwatch();
            Stopwatch sw_IS        = new Stopwatch();
            Stopwatch sw_BandB     = new Stopwatch();

            sw_all.Start();
            string test_case = "沪杭";                     //"BigScale";////

            CrewRules.All_Num_Crew = 240;                //京津-60;沪杭-240;bigscal-300;bigscal2-400
            string     data_dir = @"\data\" + test_case; //京津";
            DataReader Data     = new DataReader();

            List <string> csvfiles;

            Data.Connect_csvs(out csvfiles, data_dir);
            Data.LoadRules_csv(); //该函数并未考虑时间窗
            //考虑时间窗的话,为了测试方便,直接在代码里设置时间窗的参数,而不是放在文件中

            Data.CrewRules.DisplayRules();
            Data.LoadData_csv(Data.CrewRules.MaxDays);

            sw_creat_net.Start();
            NetWork Net = new NetWork();

            Net.CreateNetwork(Data);
            Net.IsAllTripsCovered();
            sw_creat_net.Stop();

            sw_IS.Start();
            //检查无误
            InitialSolution IS = new InitialSolution(Net);

            //IS.GetFeasibleSolutionByPenalty();
            IS.GetFeasibleSolutionByMethod1();//顺逆向标号在多基地时有问题:如对点i,顺向时最短路对应基地为B1,逆向时最短路对应基地为B2.错误
            sw_IS.Stop();

            Report Report_IS = new Report(IS.PathSet);

            Console.WriteLine(Report_IS.TransferSolution());
            Console.WriteLine("平均纯乘务时间:{0} 平均换乘时间{1} 平均task数{2}", Report_IS.summary_mean.mean_PureCrew,
                              Report_IS.summary_mean.mean_Trans, Report_IS.summary_mean.mean_Tasks);
            //string initial_solution_dir = System.Environment.CurrentDirectory + "\\结果\\京津\\初始解.txt";
            string initial_solution_dir = System.Environment.CurrentDirectory + "\\结果\\" + test_case + "\\初始解.txt";

            //Report_IS.WriteCrewPaths(@"D:\代码项目\C#\CG-version2.1_cost_1440-重构\CG_CSP_1440\jj158ISS_LineList.txt");
            Report_IS.WriteCrewPaths(initial_solution_dir);
            Console.WriteLine(sw_IS.Elapsed.TotalSeconds);
            //checked:OK
            /*********<<下面开始测试CG>>***************************************************************************/
            sw_BandB.Start();
            CSP csp = new CSP(Net);

            csp.testCase = test_case;
            csp.Branch_and_Price(IS);
            sw_BandB.Stop();
            sw_all.Stop();

            StreamWriter obj_iter = new StreamWriter(System.Environment.CurrentDirectory + "\\结果\\" + test_case + "\\OBJ迭代.csv");

            obj_iter.WriteLine("ObjValue");
            foreach (var obj in csp.obj_iter)
            {
                obj_iter.WriteLine(obj);
            }
            obj_iter.Close();


            string       path     = System.Environment.CurrentDirectory + "\\结果\\" + test_case + "\\求解信息.txt";
            FileStream   fs       = new FileStream(path, FileMode.Create);
            StreamWriter strwrite = new StreamWriter(fs);

            strwrite.WriteLine("建网时间:{0}", sw_creat_net.Elapsed.TotalSeconds);
            strwrite.WriteLine("接续弧的数量:{0}", Net.ArcSet.Count());
            strwrite.WriteLine("网络中节点数量:{0}", Net.NodeSet.Count());
            strwrite.WriteLine("初始解产生时间:{0}", sw_IS.Elapsed.TotalSeconds);
            strwrite.WriteLine("分支定界用时:{0}", sw_BandB.Elapsed.TotalSeconds);
            strwrite.WriteLine("总乘务组数量:{0}", csp.num_all_crew);
            strwrite.WriteLine("模型总共求解时间:{0}", sw_all.Elapsed.TotalSeconds);
            strwrite.WriteLine("总目标函数:{0}", /*csp.OBJVALUE);*/ csp.All_obj);
            strwrite.WriteLine("最短路总计算次数:{0}", csp.total_nums_rcspp);
            strwrite.WriteLine("初始解列数:{0}", IS.PathSet.Count);
            strwrite.WriteLine("列池总数:{0}", csp.ColumnPool.Count);
            strwrite.Close();
            fs.Close();

            string dualprice_iter = System.Environment.CurrentDirectory + "\\结果\\" + test_case + "\\对偶乘子迭代.csv";

            strwrite = new StreamWriter(dualprice_iter, false, Encoding.Default);
            //strwrite.WriteLine("iter,dual_price");
            csp.task_dualPrice.OrderBy(k => k.Key).ToDictionary(k => k.Key, v => v.Value);
            int i = 0;

            for (i = 1; i < csp.task_dualPrice.Keys.Count; i++)
            {
                strwrite.Write("task" + i + ",");
            }
            strwrite.WriteLine("task" + i);
            for (int j = 0; j < csp.task_dualPrice[1].Count; j++)
            {
                for (i = 1; i < csp.task_dualPrice.Keys.Count; i++)
                {
                    strwrite.Write(csp.task_dualPrice[i][j] + ",");
                }
                strwrite.WriteLine(csp.task_dualPrice[i][j]);
            }
            strwrite.Close();

            string num_label_iter = System.Environment.CurrentDirectory + "\\结果\\" + test_case + "\\标号数量与求解时间迭代(2).csv";

            strwrite = new StreamWriter(num_label_iter, false, Encoding.Default);
            strwrite.WriteLine("iter,label num,time*10000");
            for (i = 0; i < csp.num_label_iter.Count; i++)
            {
                strwrite.WriteLine(i + 1 + "," + csp.num_label_iter[i] + "," + csp.time_rcspp[i] * 10000);
            }
            strwrite.Close();

            //string time_rcspp_iter = System.Environment.CurrentDirectory + "\\结果\\" + test_case + "\\最短路求解时间迭代.csv";
            //strwrite = new StreamWriter(time_rcspp_iter, false, Encoding.Default);
            //strwrite.WriteLine("iter,time");
            //for (i = 0; i < csp.time_rcspp.Count; i++)
            //{
            //    strwrite.WriteLine(i+1 + "," );
            //}
            //strwrite.Close();
        }
Exemple #10
0
        static void Main(string[] args)
        {
            string data_path = "Server = PC-201606172102\\SQLExpress;DataBase = 乘务计划;Integrated Security = true";
            /*--LOAD DATA FROM SQL--*/
            NetWork Network = new NetWork();

            Network.CreateNetwork(data_path);
            Network.IsAllTripsCovered();
            //建网,一天的没问题,但未删除出入度为0的点与弧
            //出度为0,说明到达站不在乘务基地,说明其到达时间太晚,无法接续 其他到站为乘务基地的车次
            //入度为0,说明出发站不在乘务基地,说明其出发时间太早,发站为乘务基地的车次 无法接续 到它
            //两天的网,再说
            System.Diagnostics.Stopwatch Net_start = new System.Diagnostics.Stopwatch();
            Net_start.Start();
            InitialSolution IS = new InitialSolution(Network); //京津,200车次,初始解耗时:107s;建网仅0.6s

            IS.GetFeasibleSolutionByPenalty();                 //Add 2-21-2019
            Net_start.Stop();
            TimeSpan initiail_solution = Net_start.Elapsed;

            Console.WriteLine("time for get inition solution : " + initiail_solution.TotalSeconds);

            //test path content of initial feasible solution
            List <Pairing> initial_Paths = new List <Pairing>();

            initial_Paths = IS.PathSet;
            Node trip  = new Node();
            int  count = 0;
            int  i;

            foreach (Pairing path in initial_Paths)
            {
                Console.WriteLine("route " + count);
                for (i = 0; i < path.Arcs.Count; i++)
                {
                    trip = path.Arcs[i].D_Point;
                    Console.Write(trip.ID + " -> ");
                }
                count++;
            }


            /*--BRANCH AND PRICE--*/
            CSP Csp = new CSP(Network);

            //Csp.Build_RMP(IS);
            Csp.Build_RMP(IS);
            Csp.LinearRelaxation();

            string LP_result_schedule = "C:\\Users\\Administrator\\Desktop\\LP_CYY2.txt";
            //Csp.WriteCrewPaths(LP_result_schedule);

            Cplex          masterModel = Csp.masterModel;
            List <INumVar> vars        = Csp.DvarSet;

            //masterModel.WriteSolutions("D:\\Crew_Solution.txt");
            masterModel.ExportModel("D:\\MP2.lp");

            int j;

            count = 0;
            for (i = 0; i < vars.Count; i++)
            {
                if (masterModel.GetValue((INumVar)(vars[i])) >= 0.5)
                {
                    for (j = 0; j < Csp.PathSet[i].Arcs.Count; j++)
                    {
                        Console.Write(Csp.PathSet[i].Arcs[j].D_Point.ID + " -> ");
                    }
                    //Console.WriteLine();
                    Console.WriteLine("route " + count++);
                }
            }

            for (int t = 0; t < vars.Count; t++)
            {
                masterModel.Add(masterModel.Conversion((INumVar)vars[t], NumVarType.Int));
            }
            //masterModel.SetParam(Cplex.IntParam.VarSel, 3);//强分支
            //masterModel.SetParam(Cplex.DoubleParam.EpGap, 0.05);//相对GAP
            masterModel.SetParam(Cplex.DoubleParam.TiLim, 1800);//求解时间1200s
            masterModel.Solve();
            masterModel.WriteSolutions("D:\\IP_Solutions");

            string IP_result_schedule = "C:\\Users\\Administrator\\Desktop\\IP_Crew_Schedule2.txt";

            //Csp.WriteCrewPaths(IP_result_schedule);

            count = 0;
            for (i = 0; i < vars.Count; i++)
            {
                if (masterModel.GetValue((INumVar)(vars[i])) >= 0.5)
                {
                    for (j = 0; j < Csp.PathSet[i].Arcs.Count; j++)
                    {
                        Console.Write(Csp.PathSet[i].Arcs[j].D_Point.ID + " -> ");
                    }
                    //Console.WriteLine();
                    Console.WriteLine("route " + count++);
                }
            }
            int all_covered_num = 0; count = 0;

            int[] trip_coverd = new int[151];
            for (i = 0; i < 151; i++)
            {
                trip_coverd[i] = 0;
            }
            for (i = 0; i < vars.Count; i++)
            {
                if (masterModel.GetValue((INumVar)(vars[i])) >= 0.5)
                {
                    Console.Write("route " + (++count) + ",");
                    Console.Write(Csp.PathSet[i].Arcs.Count - 1 + "\t");
                    all_covered_num = all_covered_num + Csp.PathSet[i].Arcs.Count - 1;
                    Node trip2 = new Node();
                    for (j = 0; j < Csp.PathSet[i].Arcs.Count; j++)
                    {
                        if (Csp.PathSet[i].Arcs[j].O_Point.LineID != 0)
                        {
                            for (int k = 0; k < 151; k++)
                            {
                                if (Csp.PathSet[i].Arcs[j].O_Point.LineID == (k + 1))
                                {
                                    trip_coverd[k]++;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            Console.WriteLine("all covered node num:" + all_covered_num);
            for (int t = 0; t < trip_coverd.Length; t++)
            {
                if (trip_coverd[t] < 1)
                {
                    Console.Write("<< trip" + (t + 1) + " coverd " + trip_coverd[t] + " times " + " >>  ");
                }
            }
        }