Skip to content

Instantly share code, notes, and snippets.

@evandiewald
Created August 29, 2022 01:54
Show Gist options
  • Save evandiewald/ea7bfa834cc78745a3e4a89b154d1c8b to your computer and use it in GitHub Desktop.
Save evandiewald/ea7bfa834cc78745a3e4a89b154d1c8b to your computer and use it in GitHub Desktop.
def find_best_loop(G: nx.Graph, root, target_dist, tol=1.0, min_elev: Optional[Union[int, float]] = None,
dataset: Optional[rasterio.DatasetReader] = None):
if min_elev and not dataset:
raise ValueError("If asking for elevation data, you must include a rasterio dataset")
error = 1e8
best_path = []
for n in G.nodes():
if nx.has_path(G, root, n):
shortest_path = nx.shortest_path(G, root, n)
paths = nx.all_simple_paths(G, root, n, cutoff=10)
for path in paths:
if path == shortest_path:
continue
path_loop = path + nx.shortest_path(G, n, root, weight="length")[1:]
path_diversity = len(set(path_loop)) / len(path_loop)
dist = path_length(G, path_loop)
e_new = np.abs(dist - target_dist) / path_diversity
if e_new < error:
error = e_new
best_path = path_loop
if error < tol:
if min_elev:
coords_list = path_to_coords_list(G, path_loop)
_, elev = get_elevation_profile_of_segment(dataset, coords_list)
elev_gain = elevation_gain(elev)
if elev_gain < min_elev:
continue
return best_path
return best_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment