~ihabunek/triglav

ref: f66c43139d76b7a26925de4e29498ff1473c0950 triglav/lib/triglav_web/controllers/zet/routes_controller.ex -rw-r--r-- 7.8 KiB
f66c4313Ivan Habunek Store sample trip ID in derived data, simplify schemas 4 months ago
                                                                                
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
defmodule TriglavWeb.Zet.RoutesController do
  use TriglavWeb, :controller

  alias Triglav.GeoJSON
  alias Triglav.Import.Geofabrik
  alias Triglav.Osm
  alias Triglav.Osm.Router
  alias Triglav.Schemas.Osmosis.Relation
  alias Triglav.Zet.Errors
  alias Triglav.Zet.Gtfs
  alias Triglav.Zet.Osmosis

  @error_color "#eb4d4b"

  @route_colors [
    light_blue: "#3498db",
    purple: "#8e44ad",
    green: "#27ae60",
    dark_blue: "#3742fa",
    orange: "#d35400",
    dark_gray: "#2c3e50"
  ]

  def index(conn, _params) do
    routes = Gtfs.list_routes()
    errors = Errors.list_unresolved() |> Enum.group_by(& &1.route_id)

    relations = Osmosis.list_public_transport_relations(members: true)
    {:ok, osm_state} = Geofabrik.local_state()
    gtfs_info = Gtfs.get_feed_info()

    # Relations which were not matched to any known route
    route_ids = Enum.map(routes, & &1.id)

    unmached_relations =
      Enum.filter(relations, &(Relation.ref(&1) not in route_ids))
      |> sort_by_ref()

    render(conn, "index.html",
      routes: annotate_routes(routes, relations),
      errors: errors,
      unmached_relations: unmached_relations,
      osm_state: osm_state,
      gtfs_info: gtfs_info
    )
  end

  def detail(conn, %{"id" => id}) do
    route = Gtfs.get_route(id)
    relations = Osmosis.list_public_transport_relations(ref: id, members: true)
    hierarchy = make_hierarchy(relations)

    errors = Errors.list_unresolved(route_id: id)
    relation_errors = Enum.filter(errors, & &1.relation_id) |> Enum.group_by(& &1.relation_id)
    route_errors = Enum.filter(errors, &is_nil(&1.relation_id))

    platform_members =
      relations
      |> Enum.map(& &1.id)
      |> Osmosis.list_platform_members()
      |> Enum.group_by(& &1.relation_id)

    trips = Gtfs.list_distinct_trips(route_id: route.id)
    trips_by_stop_ids = trips |> Map.new(&{&1.stops, &1})

    relations_by_stop_ids =
      for relation <- relations, Relation.is_route(relation), into: %{} do
        {Osmosis.list_gtfs_stop_ids(relation.id), relation}
      end

    annotated_trips =
      trips
      |> Enum.map(fn trip ->
        Map.put(trip, :matched_relation, Map.get(relations_by_stop_ids, trip.stops))
      end)
      |> Enum.group_by(& &1.direction_id)

    annotated_relations =
      Enum.map(relations_by_stop_ids, fn {stops, relation} ->
        Map.put(relation, :matched_trip, Map.get(trips_by_stop_ids, stops))
      end)
      |> IO.inspect()

    stops =
      trips
      |> Enum.map(& &1.stops)
      |> Enum.concat()
      |> Enum.uniq()
      |> Gtfs.list_stops_by_id()
      |> Map.new(&{&1.id, &1})

    # JSON encode stops for drawing on the map
    stops_json =
      route
      |> Gtfs.fetch_distinct_stops()
      |> Enum.map(&Map.take(&1, [:id, :name, :lat, :lon]))
      |> Jason.encode!()

    routes_geojson =
      routes_feature_collecton(relations, platform_members)
      |> Jason.encode!()

    render(conn, "detail.html",
      conn: conn,
      hierarchy: hierarchy,
      platform_members: platform_members,
      relation_errors: relation_errors,
      relations: annotated_relations,
      route: route,
      route_errors: route_errors,
      routes_geojson: routes_geojson,
      stops: stops,
      stops_json: stops_json,
      trips: annotated_trips
    )
  end

  def match(conn, %{"id" => id, "relation_id" => relation_id}) do
    trips = Gtfs.list_distinct_trips(route_id: id)
    relation = Osm.get_relation(relation_id)

    platform_members = Osmosis.list_platform_members(relation_id)

    platforms =
      platform_members
      |> Enum.map(& &1.member)
      |> Enum.filter(& &1.tags["gtfs:stop_id"])
      |> Map.new(&{&1.tags["gtfs:stop_id"], &1})

    stops =
      trips
      |> Enum.map(& &1.stops)
      |> Enum.concat()
      |> Enum.uniq()
      |> Gtfs.list_stops_by_id()
      |> Map.new(&{&1.id, &1})

    relation_stop_ids = platform_members |> Enum.map(& &1.member.tags["gtfs:stop_id"])

    diffs =
      for trip <- trips do
        diffs = List.myers_difference(relation_stop_ids, trip.stops)
        %{trip: trip, diffs: diffs, eq_count: count_eq(diffs)}
      end
      |> Enum.sort_by(& &1.eq_count, &>=/2)

    render(conn, "match.html",
      diffs: diffs,
      platforms: platforms,
      relation: relation,
      route_id: id,
      stops: stops
    )
  end

  defp count_eq(diffs) do
    diffs
    |> Enum.filter(fn {k, _} -> k == :eq end)
    |> Enum.map(fn {_, v} -> length(v) end)
    |> Enum.sum()
  end

  defp annotate_routes(routes, relations) do
    osm_stop_ids = relations |> Enum.map(& &1.id) |> Osmosis.list_gtfs_stop_ids()
    gtfs_distinct_trips = Gtfs.list_distinct_trips() |> Enum.group_by(& &1.route_id)

    for route <- routes do
      route_relations = Enum.filter(relations, &Relation.has_tag?(&1, "ref", route.id))

      osm_variants =
        route_relations
        |> Enum.map(&Map.get(osm_stop_ids, &1.id))
        |> Enum.filter(& &1)
        |> MapSet.new()

      zet_variants =
        gtfs_distinct_trips
        |> Map.get(route.id)
        |> MapSet.new(&Map.get(&1, :stops))

      counts = %{
        total: Enum.count(zet_variants),
        correct: MapSet.intersection(osm_variants, zet_variants) |> Enum.count(),
        incorrect: MapSet.difference(osm_variants, zet_variants) |> Enum.count()
      }

      hierarchy = make_hierarchy(route_relations)

      {route, hierarchy, counts}
    end
  end

  defp routes_feature_collecton(relations, platform_members) do
    colors = @route_colors |> Enum.map(fn {_, v} -> v end) |> Stream.cycle()

    relations
    |> Enum.filter(&Relation.is_route/1)
    |> Enum.zip(colors)
    |> Map.new(fn {relation, color} ->
      name = "#{relation.tags["name"]} (##{relation.id})"
      platforms = Map.get(platform_members, relation.id, [])

      route_feature = route_feature(relation, color)
      platform_features = Enum.map(platforms, &platform_feature(&1, color))
      collection = GeoJSON.feature_collection([route_feature | platform_features])

      {name, collection}
    end)
  end

  defp platform_feature(member, color) do
    stop_id = member.member.tags["gtfs:stop_id"]
    platform_color = if stop_id, do: color, else: @error_color

    GeoJSON.to_feature(member.member, %{
      name: member.member.tags["name"],
      relation_id: member.relation_id,
      sequence_id: member.sequence_id,
      gtfs_stop_id: stop_id,
      color: platform_color
    })
  end

  defp route_feature(relation, color) do
    ordered_ways = Osm.list_ordered_ways(relation)

    # Attempt to get route as a single linestring, fall back to route segments
    route_geometry =
      case Router.route_ways(ordered_ways) do
        {:ok, linestring} -> linestring
        {:error, _} -> GeoJSON.ways_to_multilinestring(ordered_ways)
      end

    GeoJSON.feature(route_geometry, %{
      id: relation.tags["id"],
      type: relation.tags["type"],
      color: color
    })
  end

  defp make_hierarchy(relations) do
    {route_masters, routes} = Enum.split_with(relations, &(Relation.type(&1) == "route_master"))

    # Add `route` relations to `route_master` relations
    route_masters =
      route_masters
      |> Enum.map(fn route_master ->
        contained_routes =
          Enum.map(route_master.members, fn member ->
            Enum.find(routes, &(&1.id == member.member_id))
          end)

        Map.put(route_master, :contained_routes, contained_routes)
      end)

    # Remove routes which were added to a master
    added_routes =
      route_masters
      |> Enum.map(& &1.contained_routes)
      |> List.flatten()

    remaining_routes = Enum.reject(routes, &(&1 in added_routes))

    Enum.concat(route_masters, remaining_routes)
  end

  defp sort_by_ref(relations) do
    Enum.sort_by(relations, fn rel ->
      if is_nil(rel.tags["ref"]) do
        0
      else
        rel.tags["ref"]
        |> String.replace(~r"[^0-9]", "")
        |> String.to_integer()
      end
    end)
  end
end