Skip to content

Commit

Permalink
update comments and spelling fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
cyschneck committed Mar 19, 2024
1 parent 9771500 commit fc71340
Show file tree
Hide file tree
Showing 9 changed files with 77 additions and 60 deletions.
16 changes: 10 additions & 6 deletions centerline_width/centerline.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Built in Python functions
# Built-in Python functions
import math
import logging
import csv

# External Python libraries (installed via pip install)
# External Python libraries
import numpy as np
import networkx as nx
from scipy import interpolate
Expand All @@ -25,6 +25,7 @@
def generateNXGraph(all_points_dict):
# Generate a NetworkX graph to find the largest graph
def distanceBetween(start, end):
# return the distance between two points on a graph
lat1 = start[0]
lat2 = end[0]
lon1 = start[1]
Expand All @@ -35,6 +36,9 @@ def distanceBetween(start, end):
(lon2 - lon1) * p)) / 2
return math.asin(math.sqrt(a))


# nodes as lat/lon positions, weighted by the distance between each position

all_connections_in_graph = nx.Graph()
node_as_keys_pos_values = {}
for start_point, end_point_list in all_points_dict.items():
Expand All @@ -58,7 +62,7 @@ def distanceBetween(start, end):
for idx, g in enumerate(components_of_subgraphs, start=1):
if len(g.nodes()) > len(nodes_of_largest_subgraph):
nodes_of_largest_subgraph = list(g.nodes())
#print("Subgraph {0}: Nodes: {1}, Edges: {2}".format(idx, len(g.nodes()), len(g.edges())))
#print(f"Subgraph {idx}: Nodes: {len(g.nodes())}, Edges: {len(g.edges())}")

return all_connections_in_graph, nodes_of_largest_subgraph

Expand Down Expand Up @@ -231,7 +235,7 @@ def smoothedCoordinates(river_object=None,
smoothed_coordinates = []
tck, *rest = interpolate.splprep(
[x_coordinates, y_coordinates],
s=0.000001) # spline prep, tck = knots - coefficeinets - degree
s=0.000001) # spline prep, tck = knots - coefficients - degree
u = np.linspace(
0, 1, interprolate_num
) # number of steps between each point (to determine smoothness)
Expand Down Expand Up @@ -652,7 +656,7 @@ def calculateRiverArea(bank_polygon=None, ellipsoid="WGS84"):
geodesic = pyproj.Geod(ellps=ellipsoid)
river_area, river_perimeter = geodesic.geometry_area_perimeter(
bank_polygon)
return abs(river_area) / 1000
return abs(river_area) / 1000 # km


def centerlineLength(centerline_coordinates=None, ellipsoid="WGS84"):
Expand All @@ -675,4 +679,4 @@ def centerlineLength(centerline_coordinates=None, ellipsoid="WGS84"):
total_length += distance_between_meters
# Set previous_pair to xy_pair for the next iteration.
previous_pair = xy_pair
return total_length / 1000
return total_length / 1000 # km
2 changes: 1 addition & 1 deletion centerline_width/error_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# ERROR CATCHES AND LOGGING FOR CLARITY WHEN USING CENTERLINE-WIDTH
########################################################################

# Built in Python functions
# Built-in Python functions
import logging
from io import StringIO

Expand Down
4 changes: 2 additions & 2 deletions centerline_width/getCoordinatesKML.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Built in Python functions
# Built-in Python functions
import re

# External Python libraries (installed via pip install)
# External Python libraries
import pandas as pd
from pykml import parser

Expand Down
4 changes: 2 additions & 2 deletions centerline_width/plotDiagrams.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Built in Python functions
# Built-in Python functions
import math
import logging

# External Python libraries (installed via pip install)
# External Python libraries
import matplotlib.pyplot as plt
from scipy.spatial import voronoi_plot_2d

Expand Down
6 changes: 3 additions & 3 deletions centerline_width/preprocessing.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Built in Python functions
# Built-in Python functions
import csv
import logging
import math
import os

# External Python libraries (installed via pip install)
from collections import Counter

# External Python libraries
import numpy as np
from shapely.geometry import Point, Polygon, LineString
from scipy.spatial import Voronoi
Expand Down
4 changes: 2 additions & 2 deletions centerline_width/relativeDistance.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Built in Python functions
# Built-in Python functions
import math

# External Python libraries (installed via pip install)
# External Python libraries
import numpy as np
import pyproj
import geopy.distance
Expand Down
Original file line number Diff line number Diff line change
@@ -1,37 +1,41 @@

# Built-in Python functions
import logging
import math

# External Python libraries
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import savgol_filter
from scipy.interpolate import interp1d

'''
measuring the asymmetry of river a la Finotello et al. 2024 -
Vegetation Enhances Curvature-Driven Dynamics in Meandering
Rivers, 2024, Nature Communication
'''

def make_logger(logname="mylog",level=logging.WARNING, log_to_file=False):

def make_logger(logname="mylog", level=logging.WARNING, log_to_file=False):

personal_note_logger = logging.getLogger()
personal_note_logger.setLevel(level)


formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(funcName)s() [line %(lineno)d] - %(message)s')
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - %(funcName)s() [line %(lineno)d] - %(message)s'
)

stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
personal_note_logger.addHandler(stream_handler)

# save to .log file
if log_to_file:
file_handler = logging.FileHandler(logname+'.log')
file_handler = logging.FileHandler(logname + '.log')
file_handler.setFormatter(formatter)
personal_note_logger.addHandler(file_handler)

return personal_note_logger


def xy_coord(centerline_coordinates: np.ndarray) -> np.ndarray:
'''
return path as x,y pairs
Expand All @@ -45,9 +49,10 @@ def xy_coord(centerline_coordinates: np.ndarray) -> np.ndarray:
x_coordinates.append(centerline_point[0])
y_coordinates.append(centerline_point[1])

return np.array(x_coordinates),np.array(y_coordinates)
return np.array(x_coordinates), np.array(y_coordinates)


def find_curvature(x: np.ndarray,y:np.ndarray)-> np.ndarray:
def find_curvature(x: np.ndarray, y: np.ndarray) -> np.ndarray:
'''
find curvature at each point on path
'''
Expand All @@ -56,11 +61,14 @@ def find_curvature(x: np.ndarray,y:np.ndarray)-> np.ndarray:
dy = np.gradient(y)
ddx = np.gradient(dx)
ddy = np.gradient(dy)
curvature_path = np.abs(dx * ddy - dy * ddx) / (dx ** 2 + dy ** 2) ** 1.5
curvature_path = np.abs(dx * ddy - dy * ddx) / (dx**2 + dy**2)**1.5

return curvature_path

def smooth_curvature(curvature_path: np.ndarray, poly_order: int = 3, window_size: int = 21) -> np.ndarray:

def smooth_curvature(curvature_path: np.ndarray,
poly_order: int = 3,
window_size: int = 21) -> np.ndarray:
'''
smooth curvature using low-pass filter (Savitzky–Golay)
'''
Expand All @@ -69,7 +77,9 @@ def smooth_curvature(curvature_path: np.ndarray, poly_order: int = 3, window_siz

return smoothed_curvature

def find_inflection_pt_index(x_points: np.ndarray,y_points: np.ndarray) -> np.ndarray:

def find_inflection_pt_index(x_points: np.ndarray,
y_points: np.ndarray) -> np.ndarray:
'''
find where the slope of the curvature
changes sign from negative to positive
Expand All @@ -89,7 +99,8 @@ def find_inflection_pt_index(x_points: np.ndarray,y_points: np.ndarray) -> np.nd
return inflection_pt_indx


def find_apex_index(smoothed_curvature: np.ndarray, inflection_pt_index: np.ndarray) -> np.ndarray:
def find_apex_index(smoothed_curvature: np.ndarray,
inflection_pt_index: np.ndarray) -> np.ndarray:
'''
find river apex indices aka points of max curvature
between successive inflection points
Expand All @@ -100,22 +111,26 @@ def find_apex_index(smoothed_curvature: np.ndarray, inflection_pt_index: np.ndar
start_index = inflection_pt_index[i]
end_index = inflection_pt_index[i + 1]
if start_index != end_index:
max_index = start_index + np.argmax(smoothed_curvature[start_index:end_index])
max_index = start_index + np.argmax(
smoothed_curvature[start_index:end_index])
apex_index.append(max_index)

return np.array(apex_index)

def streamwise_distances(x,y,start_index,end_index):

def streamwise_distances(x, y, start_index, end_index):

def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

total_dist = 0
for i in range(start_index,end_index):
total_dist += distance(x[i], y[i], x[i+1], y[i+1])
for i in range(start_index, end_index):
total_dist += distance(x[i], y[i], x[i + 1], y[i + 1])

return total_dist

def wavelength_asymmetry(x,y, apex_index, inflection_pt_index):

def wavelength_asymmetry(x, y, apex_index, inflection_pt_index):
'''
see Finotello+2024 fig. 2
Expand All @@ -124,60 +139,60 @@ def wavelength_asymmetry(x,y, apex_index, inflection_pt_index):
(ld) downstream component =
distance from apex to next inflection point (traveling downstream)
instrinic wavelength = lu + ld
intrinsic wavelength = lu + ld
'''

lu = []
ld = []
instric_wavelength = []
intrinsic_wavelength = []
asymmetry = []

mylog.warning("Something weird is happening here. "
"Not sure why the distances keep getting bigger. "
"Fix this.")
"Not sure why the distances keep getting bigger. "
"Fix this.")

for i in range(len(inflection_pt_index) - 1):
start_index = inflection_pt_index[i]
mid_index = apex_index[i]
end_index = inflection_pt_index[i+1]
lu.append(streamwise_distances(x,y,start_index,mid_index))
ld.append(streamwise_distances(x,y,mid_index,end_index))
instric_wavelength.append(lu[i] + ld[i])
asymmetry.append((lu[i] - ld[i])/instric_wavelength[i])
end_index = inflection_pt_index[i + 1]
lu.append(streamwise_distances(x, y, start_index, mid_index))
ld.append(streamwise_distances(x, y, mid_index, end_index))
intrinsic_wavelength.append(lu[i] + ld[i])
asymmetry.append((lu[i] - ld[i]) / intrinsic_wavelength[i])

return instric_wavelength, asymmetry


def main() -> None:

mylog.info('Running module RiverAsymmetry as main. Example using artifical river shape\n')
mylog.info(
'Running module RiverAsymmetry as main. Example using artificial river shape\n'
)

# RANDOM RIVER SHAPE
num_pts = 1000
scl = 0.01
t = np.linspace(0, 10*np.pi, num_pts)
t = np.linspace(0, 10 * np.pi, num_pts)
x = t
y = np.sin(t) #+ np.random.normal(scale=scl, size=num_pts)

y = np.sin(t) #+ np.random.normal(scale=scl, size=num_pts)

# CALCULATE STUFF
curv = find_curvature(x,y)
curv = find_curvature(x, y)
scurv = smooth_curvature(curv)

ip_idx = find_inflection_pt_index(t,scurv)
apex = find_apex_index(scurv,ip_idx)

wv_len, asym = wavelength_asymmetry(x,y, apex, ip_idx)
ip_idx = find_inflection_pt_index(t, scurv)
apex = find_apex_index(scurv, ip_idx)

wv_len, asym = wavelength_asymmetry(x, y, apex, ip_idx)

# PLOT STUFF

fig, axs = plt.subplots(2)
axs[0].plot(x,y,'k.-')
axs[0].plot(x, y, 'k.-')

#axs[1].plot(t,curv,'k.-', label = 'curvature')
axs[1].plot(t,scurv,'k.-', label = 'smoothed curvature')
axs[1].plot(t, scurv, 'k.-', label='smoothed curvature')

for ind in ip_idx:
axs[1].axvline(x=t[ind], color='r', linestyle='--', alpha=0.5)
Expand All @@ -193,15 +208,13 @@ def main() -> None:
plt.legend()
plt.show()


fig, axs = plt.subplots(2)
axs[0].scatter(ip_idx[:-1],wv_len,color='b')
axs[1].scatter(ip_idx[:-1],asym,color='r')
axs[0].scatter(ip_idx[:-1], wv_len, color='b')
axs[1].scatter(ip_idx[:-1], asym, color='r')
plt.show()


if __name__ == '__main__':

mylog = make_logger(level=logging.INFO)
main()

2 changes: 1 addition & 1 deletion centerline_width/riverCenterlineClass.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# River object class used for all functions and centerline functions

# External Python libraries (installed via pip install)
# External Python libraries
import pandas as pd

# Internal centerline_width reference to access functions, global variables, and error handling
Expand Down
4 changes: 2 additions & 2 deletions centerline_width/saveOutput.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Built in Python functions
# Built-in Python functions
import csv
import logging

# External Python libraries (installed via pip install)
# External Python libraries
import numpy as np
from scipy.io import savemat

Expand Down

0 comments on commit fc71340

Please sign in to comment.