def optimize_removal(solver: GraphSolver, tree: Graph, orig_cost: float): candidates = [ v for v in tree.nodes if not solver.is_required(v) and is_leaf(tree, v) ] while candidates: # print(candidates) # random.seed(0) node = random.choice(candidates) candidates.remove(node) edge = (node, list(tree.neighbors(node))[0]) solver.unvisit(node) new_cost = average_pairwise_distance(tree) if new_cost < orig_cost: # print('removed', node) return optimize_removal(solver, tree, new_cost) else: solver.add_edge(edge) return orig_cost
def optimize_removal_sorted(solver: GraphSolver, tree: Graph, orig_cost: float): candidates = [ v for v in tree.nodes if not solver.is_required(v) and is_leaf(tree, v) ] while candidates: # print(candidates) # random.seed(0) candidates.sort(key=lambda x: closeness_centrality(solver.T, x)) node = candidates.pop(0) edge = (node, list(tree.neighbors(node))[0]) solver.unvisit(node) new_cost = average_pairwise_distance(tree) if new_cost < orig_cost: # print('removed', node) return optimize_removal_sorted(solver, tree, new_cost) else: solver.add_edge(edge) return orig_cost