~ihabunek/triglav

ref: 3a1876166aa129c76c1b09fc562af764d04df4e1 triglav/lib/triglav_web/controllers/zet/routes_controller.ex -rw-r--r-- 7.2 KiB
3a187616Ivan Habunek Fix detecting unexpected master route members 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
defmodule TriglavWeb.Zet.RoutesController do
  use TriglavWeb, :controller

  alias Triglav.Derived.PublicTransport
  alias Triglav.GeoJSON
  alias Triglav.Import.Geofabrik
  alias Triglav.Osm
  alias Triglav.Repo
  alias Triglav.Schemas.Osmosis.Relation
  alias Triglav.Schemas.PublicTransport.{Platform, Trip}
  alias Triglav.Schemas.Zet
  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)
    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))

    trips = PublicTransport.list_route_trips(id)
    zet_stops = Gtfs.fetch_distinct_stops(route)
    zet_stops_map = Map.new(zet_stops, &{&1.id, &1})

    zet_trips =
      Gtfs.list_distinct_trips(route_id: route.id)
      |> Enum.map(fn trip ->
        matched_trip = Enum.find(trips, &(&1.sample_trip_id == trip.sample_trip_id))
        matched_relation = if matched_trip, do: matched_trip.relation
        stops = Enum.map(trip.stop_ids, &Map.fetch!(zet_stops_map, &1))

        trip
        |> Map.put(:matched_relation, matched_relation)
        |> Map.put(:stops, stops)
      end)
      |> Enum.group_by(& &1.direction_id)

    trips_geojson = trips_feature_collecton(trips) |> Jason.encode!()
    zet_stops_geojson = zet_stops_feature_collection(zet_stops) |> Jason.encode!()

    render(conn, "detail.html",
      conn: conn,
      trips: trips,
      hierarchy: hierarchy,
      relation_errors: relation_errors,
      relations: relations,
      route: route,
      route_errors: route_errors,
      trips_geojson: trips_geojson,
      zet_stops_geojson: zet_stops_geojson,
      zet_trips: zet_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.stop_ids)
      |> 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.stop_ids)
        %{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, :stop_ids))

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

      hierarchy = make_hierarchy(route_relations)

      {route, hierarchy, counts}
    end
  end

  defp zet_stops_feature_collection(zet_stops) do
    zet_stops
    |> Enum.map(&Zet.Stop.to_feature/1)
    |> GeoJSON.feature_collection()
  end

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

    trips
    |> Enum.zip(colors)
    |> Map.new(fn {trip, color} ->
      name = "#{trip.relation.tags["name"]} (##{trip.relation.id})"
      trip_feature = trip_feature(trip, color)
      platform_features = Enum.map(trip.platforms, &platform_feature(&1, color))
      collection = GeoJSON.feature_collection([trip_feature | platform_features])

      {name, collection}
    end)
  end

  defp platform_feature(%Platform{} = platform, color) do
    platform_color = if platform.stop_id, do: color, else: @error_color
    member = platform.node || platform.way

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

  defp trip_feature(%Trip{} = trip, color) do
    GeoJSON.feature(trip.geometry, %{
      id: trip.relation.tags["id"],
      type: trip.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 ->
        route_master = Repo.preload(route_master, :members)

        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