File size: 5,283 Bytes
1e36484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import math

import networkx
import pickle
import networkx as nx
from shapely.geometry import LineString

def _remove_isolated_nodes(G):
    isolated = list(nx.isolates(G))
    print(f"{len(isolated)} isolated edge-nodes")
    if isolated: G.remove_nodes_from(isolated)
    print(f"{len(list(nx.isolates(G)))} isolated edge-nodes")
    return G


def get_highway_type(d):
    hw = d.get("highway")
    if isinstance(hw, list):
        return hw[0]
    return hw


def _edge_midpoint(G, u, v, k, data):
    # Try to use edge geometry; fallback to straight segment between node coords
    if 'geometry' in data and isinstance(data['geometry'], LineString):
        geom = data['geometry']
    else:
        # build a simple LineString between endpoints
        xu, yu = G.nodes[u]['x'], G.nodes[u]['y']
        xv, yv = G.nodes[v]['x'], G.nodes[v]['y']
        geom = LineString([(xu, yu), (xv, yv)])
    return geom.interpolate(0.5, normalized=True)


def _linestring_bearing(ls: LineString, use_tail: bool = True) -> float:
    if use_tail:
        p1 = ls.coords[-2]
        p2 = ls.coords[-1]
    else:
        p1 = ls.coords[0]
        p2 = ls.coords[1]

    return _points_bearing(p1, p2)


def _points_bearing(p1: tuple[float, float], p2: tuple[float, float]) -> float:
    xu, yu = p1
    xv, yv = p2
    bearing = math.atan2(yv - yu, xv - xu) * 180.0 / math.pi
    return bearing % 360.0


def _edge_bearing(G, u, v, k, data, use_tail: bool = True) -> float:
    # Try to use edge geometry; fallback to straight segment between node coords
    if 'geometry' in data and isinstance(data['geometry'], LineString):
        geom = data['geometry']
        return _linestring_bearing(geom, use_tail=use_tail)
    else:
        # build a simple LineString between endpoints
        xu, yu = G.nodes[u]['x'], G.nodes[u]['y']
        xv, yv = G.nodes[v]['x'], G.nodes[v]['y']
        return _points_bearing((xu, yu), (xv, yv))


def _signed_turn_angle(bearing_from: float, bearing_to: float) -> float:
    angle = (bearing_to - bearing_from + 180) % 360 - 180
    return angle


def _default_turn_attrs(G, e_from_data, e_to_data):
    u, v, k, from_data = e_from_data
    _, w, k2, to_data = e_to_data

    bearing_from = _edge_bearing(G, u, v, k, from_data, use_tail=True)
    bearing_to = _edge_bearing(G, v, w, k2, to_data, use_tail=False)
    turn_angle = _signed_turn_angle(bearing_from, bearing_to)

    length = to_data.get('length', 1.0)
    return {'size': float(length), 'turn_angle': float(turn_angle)}


def convert_to_line_graph(G_in, disallow_uturn: bool = True, turn_cost_fn: bool = None):
    G = networkx.DiGraph()
    edge_node = {}
    node_edge = {}
    if turn_cost_fn is None:
        turn_cost_fn = _default_turn_attrs

    # 1) Generate line graph nodes from graph edges
    for i, (u, v, k, data) in enumerate(G_in.edges(keys=True, data=True)):
        nid = i  # stable integer id
        edge_node[(u, v, k)] = nid
        node_edge[nid] = (u, v, k)

        # Compute a representative point for visualization/debug
        mid = _edge_midpoint(G_in, u, v, k, data)                       # shapely Point
        bearing = _edge_bearing(G_in, u, v, k, data, use_tail=False)    # original edge direction
        x_attr, y_attr = float(mid.x), float(mid.y)

        # Copy edge attributes to the new node, and add convenience fields
        node_data = dict(data)
        node_data.update(dict(src_u=u, src_v=v, src_key=k, x=x_attr, y=y_attr, bearing=bearing, is_edge_node=True))
        G.add_node(nid, **node_data)

    # 2) Add transitions: (u->v,k) -> (v->w,k2) for all out-edges from v
    for (u, v, k, data_from) in G_in.edges(keys=True, data=True):
        n_from = edge_node[(u, v, k)]

        for _, w, k2, data_to in G_in.out_edges(v, keys=True, data=True):
            if disallow_uturn and w == u:
                continue

            n_to = edge_node[(v, w, k2)]
            attrs = dict(turn_cost_fn(G_in, (u, v, k, data_from), (v, w, k2, data_to)) or {})
            G.add_edge(n_from, n_to, **attrs)

    G = _remove_isolated_nodes(G)
    return G, edge_node, node_edge


if __name__ == "__main__":
    from graph_format import to_torch_geometric_data, to_numpy_adj
    from stats import print_graph_stats, audit_adj

    graph = "/home/dmariaa/metraq/dataset/traffic/road-network-graph.pkl"
    # graph = "/home/dmariaa/metraq/dataset/traffic/road-network/truncated_graph.pkl"
    with open(graph, "rb") as f:
        G: nx.Graph = pickle.load(f)

    disallow_uturn = True
    turn_cost_fn = None
    G_out, _, _ = convert_to_line_graph(G, disallow_uturn=disallow_uturn, turn_cost_fn=turn_cost_fn)
    print_graph_stats(G_out)

    G_pytorch = to_torch_geometric_data(G_out)
    print("="*50)
    print("Pytorch Geometric Data:")
    print(f"Number of nodes: {G_pytorch.num_nodes}")
    print(f"Number of edges: {G_pytorch.num_edges}")
    print(f"Number of features per node: {G_pytorch.num_node_features}")
    print(f"Contains isolated nodes? {G_pytorch.has_isolated_nodes()}")
    print(f"Contains self-loops? {G_pytorch.has_self_loops()}")
    print(f"Is undirected? {G_pytorch.is_undirected()}")

    G_adj = to_numpy_adj(G_out)
    print("=" * 50)
    print(f"Adjacency matrix shape: {G_adj.shape}")
    print(audit_adj(G_adj))