I have a line vector where each segment has a randomly assigned direction. The image shows an example (which consists of two connected lines),
How to set the direction of each line so that it is consistent? That is, connected lines have the same direction?
The line vector does not have a direction attribute. This information is somehow stored in the GPKG file in some other way.
You can use line_merge. For it to work you need each cluster of connected lines to be a multiline, which can be done using GeoPandas:
from shapely.wkt import loads
import geopandas as gpd
data = [[1, 'LineString (543125 6941963, 544217 6941907)'],
[2, 'LineString (544957 6941417, 544217 6941907)'],
[3, 'LineString (544957 6941417, 545151 6942222)'],
[4, 'LineString (545882 6941574, 545854 6940094)'],
[5, 'LineString (545531 6942647, 546567 6943424)'],
[6, 'LineString (546548 6944201, 546567 6943424)'],
[7, 'LineString (546548 6944201, 547297 6944248)']]
geoms = [loads(x[1]) for x in data]
df = gpd.GeoDataFrame(data=data, geometry=geoms, columns=["line_id", "wkt"], crs=3006)
#Creata a column with buffered lines (polygon geometries)
df["buffered"] = df.buffer(100)
#Dissolve them into three polygons, each connetcting a number of lines
poly_df = df.set_geometry("buffered").dissolve().explode()
poly_df["poly_id"] = range(poly_df.shape[0]) #Give each polygon a unique id
ax = poly_df.plot(column="poly_id", zorder=0, cmap="Pastel2")
df.plot(column="line_id", ax=ax, cmap="tab10", zorder=1)
#Join the polygon id to the connected lines,
# to give connected lines the same poly_id
df["poly_id"] = df.sjoin(poly_df)["poly_id"]
#Dissolve by polygon id to union connected lines into multilines,
# line_merge to align the line directions, explode back to individual lines
df = df.dissolve(by="poly_id").line_merge().explode()