├── LICENSE └── STNetwork_Gurobi_Peter ├── Node.py ├── Train.py ├── __pycache__ ├── Node.cpython-38-Lab-Precision.pyc ├── Node.cpython-38.pyc ├── Node.cpython-39.pyc ├── Train.cpython-38.pyc └── Train.cpython-39.pyc ├── data ├── section.csv ├── station.csv └── train.csv └── main.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/Node.py: -------------------------------------------------------------------------------- 1 | from gurobipy import * 2 | 3 | # 节点类,储存流入与流出该节点的弧集 4 | class Node(): 5 | def __init__(self, sta, t): 6 | self.sta_located = sta 7 | self.t_located = t 8 | self.in_arcs = {} # 流入该节点的弧集,以trainNo为key,弧为value 9 | self.out_arcs = {} # 流出该节点的弧集,以trainNo为key, 弧为value 10 | self.trainOccupancyVar = {} # 某车是否占用该节点,1为占用,0为不占用 11 | self.occupancyVar = None 12 | def __repr__(self): 13 | return "Node: " + str(self.sta_located) + " at time " + str(self.t_located) 14 | 15 | def __str__(self): 16 | return "Node: sta_" + self.sta_located + ";" + "t_" + self.t_located 17 | 18 | def set_train_occupancy(self, trainList, model): 19 | ''' 20 | set individual train occupancy at this node according to the specific train's inflows at this node 21 | :return: 22 | ''' 23 | for train in trainList: 24 | if train.traNo not in self.in_arcs.keys() or train.traNo not in self.out_arcs.keys(): # 如果该车不走该节点 25 | continue 26 | self.trainOccupancyVar[train.traNo] = model.addVar(vtype=GRB.BINARY, 27 | name="ocup_" + str(self.sta_located) + '_' + str(self.t_located) + '_' + train.traNo) 28 | lhs = LinExpr(0) 29 | lhs.addTerms(1, self.trainOccupancyVar[train.traNo]) 30 | for in_arcs in self.in_arcs[train.traNo]: 31 | lhs.addTerms(-1, in_arcs) 32 | model.addConstr(lhs == 0) # 节点占用变量等于流入该节点的所有arc之和 33 | 34 | def set_occupancy(self, trainList, model): 35 | ''' 36 | set node occupancy, equals the sum of train occupancy at this nodes 37 | :param model: 38 | :return: 39 | ''' 40 | self.occupancyVar = model.addVar(vtype=GRB.BINARY, 41 | name="ocup_" + str(self.sta_located) + '_' + str( 42 | self.t_located)) 43 | lhs = LinExpr(0) 44 | lhs.addTerms(1, self.occupancyVar) 45 | 46 | for train in trainList: 47 | if train.traNo in self.trainOccupancyVar.keys(): 48 | lhs.addTerms(-1, self.trainOccupancyVar[train.traNo]) 49 | model.addConstr(lhs == 0) 50 | 51 | def associate_with_incoming_arcs(self, train): 52 | ''' 53 | associate node with train arcs, add incoming arcs to nodes 54 | :param train: 55 | :return: 56 | ''' 57 | sta_node = self.sta_located 58 | t_node = self.t_located 59 | 60 | if sta_node not in train.v_staList: # 若该车不经过该站,直接退出 61 | return -1 62 | 63 | # associate incoming arcs 64 | # train arc structure: key:[dep, arr], value为弧集字典(key: [t], value: arc字典, key为arc_length) 65 | if sta_node != train.v_staList[0]: # 不为第一站,则拥有上一站 66 | preSta = train.v_staList[train.v_staList.index(sta_node) - 1] # 已经考虑列车停站情况的车站集 67 | curSta = sta_node 68 | cur_arcs = train.arcs[preSta, curSta] # 这个区间/车站的所有弧 69 | for start_t in cur_arcs.keys(): 70 | arcs_from_start_t = cur_arcs[start_t] #从上一节点在start_t伸出来的arc,包括区间的一个arc和停站弧的若干个arc 71 | for arc_length, arc_var in arcs_from_start_t.items(): 72 | if (arc_length + start_t == t_node): # 若该弧流入该节点 73 | # 若不包含该车的弧列表,则先生成弧列表 74 | if train.traNo not in self.in_arcs.keys(): 75 | self.in_arcs[train.traNo] = [] 76 | self.in_arcs[train.traNo].append(arc_var) 77 | 78 | 79 | def associate_with_outgoing_arcs(self, train): 80 | ''' 81 | associate node with train arcs, add outgoing arcs to nodes 82 | :param train: 83 | :return: 84 | ''' 85 | sta_node = self.sta_located 86 | t_node = self.t_located 87 | 88 | if sta_node not in train.v_staList: 89 | return -1 90 | 91 | # associate outgoing arcs 92 | if sta_node != train.v_staList[-1]: #不为最后一站, 则拥有下一站 93 | curSta = sta_node 94 | nextSta = train.v_staList[train.v_staList.index(sta_node) + 1] 95 | cur_arcs = train.arcs[curSta, nextSta] # cur_arcs以t为key,获取各个length的arc 96 | # 由于此时判断该点是不是一些arc的出发点,则直接看t在不在arcs的key里,若在,则将arcs里这个t的所有arc放进来 97 | if t_node in cur_arcs.keys(): # 如果点t在列车区间/车站弧集当中 98 | self.out_arcs[train.traNo] = [] 99 | for arc_var in cur_arcs[t_node].values(): 100 | self.out_arcs[train.traNo].append(arc_var) -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/Train.py: -------------------------------------------------------------------------------- 1 | # Here defines the info about the trains 2 | from gurobipy import * 3 | 4 | 5 | class Train(): 6 | def __init__(self, traNo, dep_LB, dep_UB): 7 | ''' 8 | construct 9 | :param traNo: 10 | :param dep_LB: 11 | :param dep_UB: 12 | ''' 13 | self.traNo = traNo # 列车车次 14 | self.dep_LB = dep_LB # 始发时间窗下界 15 | self.dep_UB = dep_UB # 始发时间窗上界 16 | self.arcs = {} # 内含弧两个边界点的key:[dep, arr], value为弧集字典(key: [t], value: arc字典, key为arc_length) 三层字典嵌套: dep-arr => t => span 17 | # self.stop_addTime = 3 # 停车附加时分 18 | # self.start_addTime = 2 # 起车附加时分 19 | self.stop_addTime = 0 # 停车附加时分 20 | self.start_addTime = 0 # 起车附加时分 21 | self.min_dwellTime = 2 # 最小停站时分 22 | self.max_dwellTime = 15 # 最大停站时分 23 | self.depSta = None 24 | self.arrSta = None 25 | self.v_staList = [] # dual stations 26 | self.staList = [] # actual stations 27 | self.linePlan = {} # 开行方案字典 28 | self.nodeOccupancy = {} # 是否占用某节点,key为sta => t 29 | self.timetable = {} # 以virtual station为key,存int值 30 | self.speed = None # 列车速度,300,350 31 | 32 | def init_traStaList(self, allStaList): 33 | ''' 34 | create train staList, include s_, _t, only contains nodes associated with this train 35 | :param allStaList: 36 | :return: 37 | ''' 38 | for sta in allStaList: 39 | if sta in self.linePlan.keys(): 40 | self.staList.append(sta) 41 | self.v_staList.append('s_') 42 | for i in range(len(self.staList)): 43 | if i != 0: 44 | self.v_staList.append('_' + self.staList[i]) 45 | if i != len(self.staList) - 1: # 若不为实际车站的最后一站,则加上sta_ 46 | self.v_staList.append(self.staList[i] + '_') 47 | self.v_staList.append('_t') 48 | 49 | def create_arcs_GRB(self, secTimes, model, TimeSpan): 50 | self.depSta = self.staList[0] 51 | self.arrSta = self.staList[-1] 52 | ''' 53 | create train arcs 54 | :param v_staList: 55 | :param secTimes: 56 | :param model: 57 | :return: 58 | ''' 59 | minArr = self.dep_LB # for curSta 60 | maxArr = self.dep_UB # for curSta 61 | ''' 62 | create arcs involving node s 63 | ''' 64 | self.arcs['s_', self.staList[0] + '_'] = {} 65 | for t in range(minArr, maxArr): 66 | self.arcs['s_', self.staList[0] + '_'][t] = {} # dep-arr在node t的弧集,固定区间运行时分默认只有一个元素 67 | self.arcs['s_', self.staList[0] + '_'][t][0] = model.addVar(vtype=GRB.BINARY, 68 | name=self.traNo + '_' + 's' + '_' 69 | + self.staList[0] + '_time_' + str(t)) 70 | ''' 71 | create arcs between real stations 72 | ''' 73 | for i in range(len(self.staList) - 1): 74 | curSta = self.staList[i] 75 | nextSta = self.staList[i + 1] 76 | # virtual dual stations 77 | curSta_dep = curSta + "_" 78 | nextSta_arr = "_" + nextSta 79 | nextSta_dep = nextSta + "_" 80 | 81 | secRunTime = secTimes[curSta, nextSta] # 区间运行时分 82 | 83 | # 创建两个弧, 一个运行弧,一个停站弧 84 | ''' 85 | curSta_dep-->nextSta_arr区间运行弧 86 | ''' 87 | self.arcs[curSta_dep, nextSta_arr] = {} 88 | secRunTime += self.stop_addTime # 添加停车附加时分 89 | 90 | if self.linePlan[curSta] == 1: # 本站停车, 加起停附加时分 91 | secRunTime += self.start_addTime 92 | # 设置d-a的区间运行弧 93 | for t in range(minArr, maxArr): 94 | if t + secRunTime > TimeSpan: # 如果当前t已超过horizon,直接break 95 | break 96 | self.arcs[curSta_dep, nextSta_arr][t] = {} # dep-arr在node t的弧集,固定区间运行时分默认只有一个元素 97 | self.arcs[curSta_dep, nextSta_arr][t][secRunTime] = model.addVar(vtype=GRB.BINARY, 98 | name=self.traNo + '_' + curSta_dep + '_' 99 | + nextSta_arr + '_time_' + str( 100 | t)) 101 | # 灵活运行时分弧,散点为1 102 | # self.arcs[curSta_dep, nextSta_arr][t][secRunTime + 1] = model.addVar(vtype=GRB.CONTINUOUS, 103 | # name=self.traNo + '_' + curSta_dep + '_' 104 | # + nextSta_arr + '_time_' + str( 105 | # t)) 106 | # update cur time window 107 | minArr += secRunTime 108 | maxArr = min(maxArr + secRunTime, TimeSpan) 109 | if minArr > maxArr: # 如果最早的弧当前都要越界, break掉 110 | break 111 | ''' 112 | nextSta_arr-->nextSta_dep车站停站弧 113 | ''' 114 | if i + 1 == len(self.staList) - 1: # 若停站, 但已经是最后一个站了,不需停站弧 115 | break 116 | 117 | self.arcs[nextSta_arr, nextSta_dep] = {} 118 | if self.linePlan[nextSta] == 1: # 该站停车,创建多个停站时间长度的停站弧 119 | for t in range(minArr, maxArr): 120 | if t + self.min_dwellTime > TimeSpan: # 当前t加上最短停站时分都超了,break掉 121 | break 122 | self.arcs[nextSta_arr, nextSta_dep][t] = {} 123 | for span in range(self.min_dwellTime, self.max_dwellTime): 124 | if t + span > TimeSpan: 125 | break 126 | self.arcs[nextSta_arr, nextSta_dep][t][span] = model.addVar(vtype=GRB.BINARY, 127 | name=self.traNo + '_' + nextSta_arr 128 | + nextSta_dep + '_time_' + str( 129 | t)) 130 | else: # 该站不停车,只创建一个竖直弧,长度为0 131 | for t in range(minArr, maxArr): 132 | self.arcs[nextSta_arr, nextSta_dep][t] = {} 133 | self.arcs[nextSta_arr, nextSta_dep][t][0] = model.addVar(vtype=GRB.BINARY, 134 | name=self.traNo + '_' + nextSta_arr 135 | + nextSta_dep + '_time_' + str( 136 | t)) 137 | # update cur time window 138 | minArr += self.min_dwellTime 139 | maxArr = min(maxArr + self.max_dwellTime, TimeSpan) 140 | if minArr > maxArr: 141 | break 142 | ''' 143 | create arcs involving node t 144 | ''' 145 | self.arcs['_' + self.staList[-1], '_t'] = {} 146 | for t in range(minArr, maxArr): 147 | self.arcs['_' + self.staList[-1], '_t'][t] = {} # dep-arr在node t的弧集,固定区间运行时分默认只有一个元素 148 | self.arcs['_' + self.staList[-1], '_t'][t][0] = model.addVar(0, 1, vtype=GRB.BINARY, 149 | name=self.traNo + '_' + self.staList[-1] + '_' 150 | + 't' + '_time_' + str(t)) 151 | 152 | 153 | -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/__pycache__/Node.cpython-38-Lab-Precision.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Peter1sCoding/TrainTimetable_SpaceTimeNetwork_Gurobi/32c8520822f317039dae94d64ceb3a5e840de357/STNetwork_Gurobi_Peter/__pycache__/Node.cpython-38-Lab-Precision.pyc -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/__pycache__/Node.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Peter1sCoding/TrainTimetable_SpaceTimeNetwork_Gurobi/32c8520822f317039dae94d64ceb3a5e840de357/STNetwork_Gurobi_Peter/__pycache__/Node.cpython-38.pyc -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/__pycache__/Node.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Peter1sCoding/TrainTimetable_SpaceTimeNetwork_Gurobi/32c8520822f317039dae94d64ceb3a5e840de357/STNetwork_Gurobi_Peter/__pycache__/Node.cpython-39.pyc -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/__pycache__/Train.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Peter1sCoding/TrainTimetable_SpaceTimeNetwork_Gurobi/32c8520822f317039dae94d64ceb3a5e840de357/STNetwork_Gurobi_Peter/__pycache__/Train.cpython-38.pyc -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/__pycache__/Train.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Peter1sCoding/TrainTimetable_SpaceTimeNetwork_Gurobi/32c8520822f317039dae94d64ceb3a5e840de357/STNetwork_Gurobi_Peter/__pycache__/Train.cpython-39.pyc -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/data/section.csv: -------------------------------------------------------------------------------- 1 | station,runtime(300),runtime(350) 2 | A-B,10,9 3 | B-C,20,18 4 | C-D,14,12 5 | D-E,8,7 6 | E-F,8,7 7 | F-G,10,8 8 | -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/data/station.csv: -------------------------------------------------------------------------------- 1 | station,mile 2 | A,0 3 | B,50 4 | C,100 5 | D,170 6 | E,210 7 | F,250 8 | G,300 9 | -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/data/train.csv: -------------------------------------------------------------------------------- 1 | trainNO,speed,A,B,C,D,E,F,G 2 | G1,350,1,0,0,0,0,1,1 3 | G3,350,1,1,1,0,1,0,1 4 | G5,350,1,1,0,1,0,1,1 5 | G7,350,1,1,0,0,1,0,1 6 | G9,350,1,1,0,0,0,1,1 7 | G11,350,1,1,0,0,1,0,1 8 | G13,300,1,1,1,1,1,1,1 9 | G15,300,1,1,1,1,1,1,1 10 | G17,300,1,1,1,1,1,1,1 11 | G19,300,1,1,1,1,1,1,1 12 | G21,300,1,1,1,1,1,1,1 13 | G23,300,1,1,1,1,1,1,1 14 | G25,300,1,1,1,1,1,1,1 15 | G27,300,1,1,1,1,1,1,1 16 | G29,300,1,1,1,1,1,1,1 17 | G31,300,1,1,1,1,1,1,1 18 | -------------------------------------------------------------------------------- /STNetwork_Gurobi_Peter/main.py: -------------------------------------------------------------------------------- 1 | import regex 2 | 3 | from Train import * 4 | from gurobipy import * 5 | from Node import * 6 | import matplotlib.pyplot as plt 7 | import numpy as np 8 | import csv 9 | 10 | model = Model('TTP_TimeSpaceNetwork') 11 | TimeSpan = 160 12 | H_dep = 5 13 | H_arr = 5 14 | ''' 15 | initialize stations, sections, trains and train arcs 16 | ''' 17 | staList = [] # 实际车站列表 18 | v_staList = [] # 时空网车站列表,车站一分为二 # 源节点s, 终结点t 19 | secTimes_300 = {} # total miles for stations 20 | secTimes_350 = {} # total miles for stations 21 | miles = [] 22 | trainList = [] 23 | nodeList = {} # 先用车站做key,再用t做key索引到node 24 | 25 | 26 | def readStation(path): 27 | f = open(path, 'r') 28 | lines = f.readlines() 29 | count = 0 30 | for line in lines: 31 | if count == 0: 32 | count += 1 33 | continue 34 | 35 | line = line[:-1] 36 | str = re.split(r",", line) 37 | staList.append(str[0]) 38 | miles.append(int(str[1])) 39 | for sta in staList: 40 | if staList.index(sta) != 0: # 不为首站,有到达 41 | v_staList.append('_' + sta) 42 | if staList.index(sta) != len(staList) - 1: 43 | v_staList.append(sta + '_') # 不为尾站,又出发 44 | 45 | 46 | def readSection(path): 47 | f = open(path, 'r') 48 | lines = f.readlines() 49 | count = 0 50 | for line in lines: 51 | if count == 0: 52 | count += 1 53 | continue 54 | line = line[:-1] 55 | str = re.split(r",", line) 56 | pair = re.split(r"-", str[0]) 57 | secTimes_300[pair[0], pair[1]] = int(str[1]) 58 | secTimes_350[pair[0], pair[1]] = int(str[2]) 59 | 60 | 61 | def readTrain(path): 62 | f = open(path, 'r') 63 | lines = f.readlines() 64 | count = 0 65 | for line in lines: 66 | if count == 0: 67 | count += 1 68 | continue 69 | line = line[:-1] 70 | str = re.split(r",", line) 71 | train = Train(str[0], 0, TimeSpan) 72 | train.speed = str[1] 73 | for i in range(0, len(staList)): 74 | if (str[i + 2] == '1'): 75 | train.linePlan[staList[i]] = 1 76 | else: 77 | train.linePlan[staList[i]] = 0 78 | train.init_traStaList(staList) 79 | if train.speed == '350': 80 | train.create_arcs_GRB(secTimes_350, model, TimeSpan) 81 | else: 82 | train.create_arcs_GRB(secTimes_300, model, TimeSpan) 83 | trainList.append(train) 84 | 85 | 86 | readStation('data/station.csv') 87 | readSection('data/section.csv') 88 | readTrain('data/train.csv') 89 | 90 | 91 | def init_nodes(): 92 | ''' 93 | initialize nodes, associated with incoming nad outgoing train arcs 94 | ''' 95 | # initialize node dictionary with key [sta][t] 96 | for sta in v_staList: # 循环车站 97 | nodeList[sta] = {} 98 | for t in range(0, TimeSpan): # 循环时刻t 99 | node = Node(sta, t) 100 | nodeList[sta][t] = node 101 | 102 | 103 | # associate node with train arcs, add incoming and outgoing arcs to nodes 104 | def associate_arcs(trainList): 105 | for nodes_sta in nodeList.values(): 106 | for node in nodes_sta.values(): 107 | for train in trainList: 108 | node.associate_with_outgoing_arcs(train) 109 | node.associate_with_incoming_arcs(train) 110 | 111 | 112 | ''' 113 | complementary methods 辅助方法,生成车站到达与出发的key 114 | ''' 115 | def get_arrSta(arr): 116 | return '_' + arr 117 | 118 | 119 | def get_depSta(dep): 120 | return dep + '_' 121 | 122 | 123 | ''' 124 | set flow balance constraints 125 | ''' 126 | source_node = 's_' 127 | sink_node = '_t' 128 | 129 | 130 | def set_minimize_travel_time_Obj(model): 131 | obj = LinExpr() 132 | for train in trainList: 133 | # dep-arr => t => span 134 | for i in range(1, len(train.v_staList) - 1): 135 | curSta = train.v_staList[i] 136 | nextSta = train.v_staList[i + 1] 137 | for t, arcs_t in train.arcs[curSta, nextSta].items(): 138 | for arc_length, arc_var in arcs_t.items(): 139 | obj.addTerms(arc_length, arc_var) 140 | model.setObjective(obj, GRB.MINIMIZE) 141 | 142 | 143 | def set_source_flow_Constr(model): 144 | # source node arc => only one arc exists, source dep: 's_' 145 | for train in trainList: 146 | lhs = LinExpr(0) 147 | for t_arcs in train.arcs[source_node, get_depSta(train.depSta)].values(): 148 | # default: only possess one arc(key: 0) 149 | lhs.addTerms(1, t_arcs[0]) 150 | model.addConstr(lhs == 1) 151 | 152 | 153 | def set_sink_flow_Constr(model): 154 | # sink node arc => only one arc exists, sink arr: '_t' 155 | for train in trainList: 156 | lhs = LinExpr(0) 157 | for t_arcs in train.arcs[get_arrSta(train.arrSta), '_t'].values(): 158 | # default: only possess one arc(key: 0), note: _E, _t 159 | lhs.addTerms(1, t_arcs[0]) 160 | model.addConstr(lhs == 1) 161 | 162 | 163 | def set_flow_balance_Constr(model): 164 | # flow balance during actual stations 165 | # for a specific train at any node it passes, flow balance must be kept 166 | for train in trainList: 167 | for i in range(1, len(train.v_staList) - 1): # 去掉虚拟节点 168 | sta = train.v_staList[i] 169 | for t in range(0, TimeSpan): 170 | node = nodeList[sta][t] 171 | lhs = LinExpr(0) # 对每一个车在每一个time space node都有一个约束,流入等于流出 172 | if train.traNo in node.in_arcs.keys() and train.traNo in node.out_arcs.keys(): # 若该train有同时流入和流出该节点的弧 173 | for arc in node.in_arcs[train.traNo]: 174 | lhs.addTerms(1, arc) 175 | for arc in node.out_arcs[train.traNo]: 176 | lhs.addTerms(-1, arc) 177 | model.addConstr(lhs == 0) 178 | 179 | 180 | def set_node_occupancy_variables(model): 181 | for sta, nodes in nodeList.items(): 182 | for node in nodes.values(): 183 | node.set_train_occupancy(trainList, model) # set specific train occupancy at node, arc related 184 | node.set_occupancy(trainList, model) # set node occupancy, all trains related 185 | 186 | 187 | def set_headway_constraint(model): 188 | ''' 189 | for each departure node in graph 190 | no successive occupancies for nodes within the time interval of the departure headway 191 | :return: 192 | ''' 193 | for sta in v_staList: 194 | for t in range(0, TimeSpan): 195 | H = 0 196 | if sta.endswith('_'): 197 | H = H_dep 198 | elif sta.startswith('_'): 199 | H = H_arr 200 | if t + H - 1 >= TimeSpan: 201 | break 202 | lhs = LinExpr(0) 203 | for t_range in range(0, H): 204 | node = nodeList[sta][t + t_range] 205 | if node.occupancyVar is not None: 206 | lhs.addTerms(1, node.occupancyVar) 207 | model.addConstr(lhs <= 1) 208 | 209 | 210 | def get_train_paths_from_result(): 211 | for train in trainList: 212 | print("===============Tra_" + train.traNo + "======================") 213 | for i in range(len(train.v_staList) - 1): 214 | curSta = train.v_staList[i] 215 | nextSta = train.v_staList[i + 1] 216 | for t, arcs_t in train.arcs[curSta, nextSta].items(): 217 | for arc_length, arc_var in arcs_t.items(): 218 | if (arc_var.x == 1): 219 | print(curSta + "(" + str(t) + ") => " + nextSta + "(" + str(t + arc_length) + ")") 220 | train.timetable[curSta] = t 221 | train.timetable[nextSta] = t + arc_length 222 | for sta in v_staList: 223 | for t in range(0, TimeSpan): 224 | if nodeList[sta][t].occupancyVar.x == 1: 225 | print(sta + "-" + str(t) + " is occupied") 226 | 227 | 228 | ''' 229 | initialization 230 | ''' 231 | # init_trains() 232 | init_nodes() 233 | associate_arcs(trainList=trainList) 234 | 235 | ''' 236 | flow balance constraints 237 | ''' 238 | set_source_flow_Constr(model) 239 | set_sink_flow_Constr(model) 240 | set_flow_balance_Constr(model) 241 | 242 | ''' 243 | variable transitions 244 | ''' 245 | set_node_occupancy_variables(model) 246 | 247 | ''' 248 | track capacity constraint 249 | ''' 250 | set_headway_constraint(model) 251 | 252 | ''' 253 | objective function 254 | ''' 255 | set_minimize_travel_time_Obj(model) 256 | 257 | ''' 258 | solve and get result 259 | ''' 260 | model.optimize() 261 | model.write('model.lp') 262 | get_train_paths_from_result() 263 | 264 | ''' 265 | draw timetable 266 | ''' 267 | fig = plt.figure(figsize=(7, 7), dpi=200) 268 | color_value = { 269 | '0': 'midnightblue', 270 | '1': 'mediumblue', 271 | '2': 'c', 272 | '3': 'orangered', 273 | '4': 'm', 274 | '5': 'fuchsia', 275 | '6': 'olive' 276 | } 277 | 278 | xlist = [] 279 | ylist = [] 280 | for i in range(len(trainList)): 281 | train = trainList[i] 282 | xlist = [] 283 | ylist = [] 284 | for sta_id in range(len(train.staList)): 285 | sta = train.staList[sta_id] 286 | if sta_id != 0: # 不为首站, 有到达 287 | if "_" + sta in train.v_staList: 288 | xlist.append(train.timetable["_" + sta]) 289 | ylist.append(miles[staList.index(sta)]) 290 | if sta_id != len(train.staList) - 1: # 不为末站,有出发 291 | if sta + "_" in train.v_staList: 292 | xlist.append(train.timetable[sta + "_"]) 293 | ylist.append(miles[staList.index(sta)]) 294 | plt.plot(xlist, ylist, color=color_value[str(i % 7)], linewidth=1.5) 295 | plt.text(xlist[0] + 0.8, ylist[0] + 4, train.traNo, ha='center', va='bottom', 296 | color=color_value[str(i % 7)], weight='bold', family='Times new roman', fontsize=9) 297 | 298 | plt.grid(True) # show the grid 299 | plt.ylim(0, miles[-1]) # y range 300 | 301 | plt.xlim(0, TimeSpan) # x range 302 | plt.xticks(np.linspace(0, TimeSpan, int(TimeSpan / 10 + 1))) 303 | 304 | plt.yticks(miles, staList, family='Times new roman') 305 | plt.xlabel('Time (min)', family='Times new roman') 306 | plt.ylabel('Space (km)', family='Times new roman') 307 | plt.savefig('Gurobi_LP.pdf', bbox_inches = 'tight') 308 | plt.show() 309 | --------------------------------------------------------------------------------