Last active
December 13, 2019 13:26
-
-
Save aialenti/da8eeabe487b51fb7090117c5856b8f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def build_graph_from_current_solution(self): | |
varsdict = {} | |
for v in self.santa.variables(): | |
if v.varValue == 1: | |
varsdict[v.name] = v.varValue | |
G = nx.Graph() | |
# Add nodes to the Graph | |
for index_a, row_a in self.cities.iterrows(): | |
lat_a = row_a["lat"] | |
lng_a = row_a["lng"] | |
G.add_node(index_a, pos=(lat_a, lng_a)) | |
# Add edges according to solution | |
for k in varsdict: | |
tmp_node = self.variables_dict[k] | |
G.add_edge(tmp_node[0], tmp_node[1]) | |
return G | |
def add_subtour_constraints(self): | |
# Generate the graph from the current solution | |
varsdict = {} | |
for v in self.santa.variables(): | |
if v.varValue == 1: | |
varsdict[v.name] = v.varValue | |
G = nx.Graph() | |
# Add nodes to the Graph | |
for index_a, row_a in self.cities.iterrows(): | |
lat_a = row_a["lat"] | |
lng_a = row_a["lng"] | |
G.add_node(index_a, pos=(lat_a, lng_a)) | |
# Add edges according to solution | |
for k in varsdict: | |
tmp_node = self.variables_dict[k] | |
G.add_edge(tmp_node[0], tmp_node[1]) | |
# If the number of connected components is 1, we found the optimal path | |
nr_connected_components = nx.number_connected_components(G) | |
if nr_connected_components == 1: | |
return True | |
# Otherwise we need to add the SEC equations | |
# Get all the connected components. If there are more than 1, then there are subtours | |
components = nx.connected_components(G) | |
for c in tqdm(components, total=nr_connected_components): | |
self.santa += lpSum([self.x[(a, b)] for a in c for b in c if a != b]) <= len(c) - 1 | |
print("ok") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment