~ihabunek/triglav

ref: 837d6e21f3fc80e932ea631bb402f346769c4154 triglav/lib/triglav/zet/validator.ex -rw-r--r-- 10.2 KiB
837d6e21Ivan Habunek Reorganize validator to use new data 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
defmodule Triglav.Zet.Validator do
  @moduledoc """
  Validates ZET routes in OSM based on ZET GTFS data.
  """
  alias Triglav.Schemas.Error
  alias Triglav.Schemas.Osmosis.Relation
  alias Triglav.Schemas.Osmosis.Way
  alias Triglav.Schemas.Zet.Route
  alias Triglav.Zet.Gtfs
  alias Triglav.Zet.Osmosis
  alias Triglav.Derived.PublicTransport
  alias Triglav.Schemas.PublicTransport.Platform

  defmodule ValidationData do
    @moduledoc """
    Contains data loaded from the database and used for validation.
    """

    @type t :: %__MODULE__{
            platforms_by_relation_id: %{integer() => [Platform.t()]},
            relations: [Relation.t()],
            relations_by_ref: %{binary() => [Relation.t()]},
            routes: [Route.t()],
            trips_map: %{integer() => Trip.t()},
            ways_map: %{integer() => Way.t()}
          }

    defstruct [
      :platforms_by_relation_id,
      :relations,
      :relations_by_ref,
      :routes,
      :trips_map,
      :ways_map
    ]
  end

  def load_data() do
    routes = Gtfs.list_routes()
    relations = Osmosis.list_public_transport_relations(members: true)
    relations_by_ref = Enum.group_by(relations, & &1.tags["ref"])
    trips = PublicTransport.list_trips()
    trips_map = trips |> Map.new(&{&1.relation_id, &1})
    platforms = PublicTransport.list_platforms()
    platforms_by_relation_id = Enum.group_by(platforms, & &1.relation_id)

    # Ways are only used for finding where routes are broken, so only fetch ways
    # for broken relations.
    broken_relations_ids = trips |> Enum.filter(&(not &1.exact)) |> Enum.map(& &1.relation_id)
    ways = relations |> Enum.filter(&(&1.id in broken_relations_ids)) |> Osmosis.list_ways()
    ways_map = Map.new(ways, &{&1.id, &1})

    %ValidationData{
      platforms_by_relation_id: platforms_by_relation_id,
      relations: relations,
      relations_by_ref: relations_by_ref,
      routes: routes,
      trips_map: trips_map,
      ways_map: ways_map
    }
  end

  @spec validate_all_routes() :: [Error.t()]
  def validate_all_routes() do
    data = load_data()

    data.routes
    |> Enum.map(&validate_route(&1, data))
    |> List.flatten()
  end

  @spec validate_route(Route.t(), ValidationData.t()) :: [Error.t()]
  def validate_route(route, data) do
    relations = Enum.filter(data.relations, &(Relation.ref(&1) == route.id))

    route_errors =
      relations
      |> Enum.filter(&Relation.is_route/1)
      |> Enum.map(&validate_route_relation(route, &1, data))

    route_master_errors =
      relations
      |> Enum.filter(&Relation.is_route_master/1)
      |> Enum.map(&validate_route_master_relation(route, &1))

    [
      validate_has_relations(route, relations),
      validate_has_route_master(route, relations),
      validate_routes_are_contained_in_route_master(route, relations),
      validate_routes_master_route_has_no_unknown_members(route, relations),
      route_errors,
      route_master_errors
    ]
    |> List.flatten()
    |> Enum.filter(& &1)
  end

  #
  # Validation fns
  #

  defp validate_has_route_master(route, relations) do
    count = Enum.count(relations, &Relation.is_route_master/1)
    all_roundtrips = Enum.all?(relations, &Relation.is_roundtrip/1)

    cond do
      count == 0 and !all_roundtrips -> Error.missing_route_master(route)
      count > 1 -> Error.multiple_route_masters(route)
      true -> nil
    end
  end

  defp validate_has_relations(route, relations) do
    if Enum.empty?(relations) do
      Error.no_relations(route)
    end
  end

  defp validate_routes_are_contained_in_route_master(route, relations) do
    route_masters = Enum.filter(relations, &Relation.is_route_master/1)

    if length(route_masters) == 1 do
      [route_master] = route_masters
      route_relations = Enum.filter(relations, &Relation.is_route/1)
      contained_ids = route_master.members |> Enum.map(& &1.member_id) |> MapSet.new()
      route_ids = route_relations |> Enum.map(& &1.id) |> MapSet.new()
      extra_ids = MapSet.difference(route_ids, contained_ids)
      extra_relations = Enum.filter(relations, &(&1.id in extra_ids))

      for relation <- extra_relations do
        Error.relation_not_contained_in_route_master(route, relation)
      end
    end
  end

  defp validate_routes_master_route_has_no_unknown_members(route, relations) do
    route_masters = Enum.filter(relations, &Relation.is_route_master/1)

    if length(route_masters) == 1 do
      [route_master] = route_masters
      routes = Enum.filter(relations, &Relation.is_route/1)
      contained_ids = route_master.members |> Enum.map(& &1.member_id) |> MapSet.new()
      route_ids = MapSet.new(routes, & &1.id)
      unexpected_ids = MapSet.difference(contained_ids, route_ids)

      for relation_id <- unexpected_ids do
        Error.unexpected_route_master_member_relation(route, relation_id)
      end
    end
  end

  # ROUTE MASTER RELATION

  defp validate_route_master_relation(%Route{} = route, %Relation{} = relation) do
    required_tags = ["type", "ref", "name", "operator"]
    allowed_tags = required_tags ++ ["route_master", "network"]

    expected_name = "#{route |> route_tag() |> String.capitalize()} #{route.id}"

    expected_tags = %{
      "route_master" => route_tag(route),
      "network" => "ZET",
      "ref" => route.id,
      "name" => expected_name
    }

    [
      validate_required_tags(route, relation, required_tags),
      validate_allowed_tags(route, relation, allowed_tags),
      validate_tag_values(route, relation, expected_tags)
    ]
  end

  defp validate_route_master_relation(_, _), do: nil

  @spec validate_route_relation(Route.t(), Relation.t(), ValidationData.t()) :: [Error.t()]
  defp validate_route_relation(
         %Route{} = route,
         %Relation{tags: %{"type" => "route"}} = relation,
         %ValidationData{} = data
       ) do
    trip = Map.get(data.trips_map, relation.id)
    platforms = Map.get(data.platforms_by_relation_id, relation.id, [])

    required_tags = ["type", "route", "ref", "operator", "from", "to", "name"]

    allowed_tags =
      Enum.concat(required_tags, ["public_transport:version", "roundtrip", "via", "network"])

    expected_tags = %{
      "route" => route_tag(route),
      "network" => "ZET",
      "ref" => route.id
    }

    [
      validate_is_ptv2(route, relation),
      validate_route_naming(route, relation),
      validate_required_tags(route, relation, required_tags),
      validate_allowed_tags(route, relation, allowed_tags),
      validate_tag_values(route, relation, expected_tags),
      validate_continuous_ways(route, relation, trip, data),
      validate_has_gtfs_stop_ids(route, relation, platforms),
      validate_member_roles(route, relation)
    ]
  end

  defp validate_is_ptv2(route, relation) do
    if !Relation.is_ptv2(relation) do
      Error.relation_not_updated_to_ptv2(route, relation)
    end
  end

  defp validate_route_naming(route, relation) do
    if Relation.has_tags?(relation, ["name", "ref", "from", "to"]) do
      actual = Relation.get_tag(relation, "name")
      ref = Relation.get_tag(relation, "ref")
      type = Relation.get_tag(relation, "route")
      from = Relation.get_tag(relation, "from")
      to = Relation.get_tag(relation, "to")
      via = Relation.get_tag(relation, "via")

      via_segments =
        if via,
          do: via |> String.split(";") |> Enum.map(&String.trim/1),
          else: []

      name_segments = [from | via_segments] ++ [to]
      expected = "#{String.capitalize(type)} #{ref}: " <> Enum.join(name_segments, " => ")

      if actual != expected do
        Error.invalid_relation_name(route, relation, actual, expected)
      end
    end
  end

  # If trip has an exact linestring, that means route is complete, so only
  # run this check if exact is false.
  defp validate_continuous_ways(route, relation, trip, data) do
    if not trip.exact do
      ordered_ways =
        relation.members
        |> Enum.filter(&(&1.member_type == "W" and &1.member_role == ""))
        |> Enum.map(fn member -> Map.fetch!(data.ways_map, member.member_id) end)

      router_result = Triglav.Osm.Router.route_ways(ordered_ways)

      case router_result do
        {:ok, _} ->
          nil

        {:error, {:ways_not_connected, _w1, w2}} ->
          Error.broken_route(route, relation, w2.id)
      end
    end
  end

  defp validate_has_gtfs_stop_ids(route, relation, platforms) do
    empty_count = Enum.count(platforms, &is_nil(&1.stop_id))

    if empty_count > 0 do
      Error.relation_missing_gtfs_stop_ids(route, relation, empty_count)
    end
  end

  defp validate_member_roles(route, relation) do
    expected_node_roles = [
      "platform",
      "platform_entry_only",
      "platform_exit_only",
      "stop",
      "stop_entry_only",
      "stop_exit_only"
    ]

    expected_way_roles = [
      "",
      "platform",
      "platform_entry_only",
      "platform_exit_only"
    ]

    if Relation.is_ptv2(relation) do
      for member <- relation.members do
        if (member.member_type == "N" and member.member_role not in expected_node_roles) or
             (member.member_type == "W" and member.member_role not in expected_way_roles) do
          Error.unexpected_member_role(route, relation, member)
        end
      end
    end
  end

  #
  # Generic relation validators
  #

  defp validate_required_tags(route, relation, required_tags) do
    required = MapSet.new(required_tags)
    existing = MapSet.new(Map.keys(relation.tags))
    missing = MapSet.difference(required, existing) |> MapSet.to_list()

    if length(missing) > 0 do
      Error.relation_missing_required_tags(route, relation, missing)
    end
  end

  defp validate_allowed_tags(route, relation, allowed_tags) do
    allowed = MapSet.new(allowed_tags)
    existing = MapSet.new(Map.keys(relation.tags))
    unexpected = MapSet.difference(existing, allowed) |> MapSet.to_list()

    if length(unexpected) > 0 do
      Error.relation_contains_unexpected_tags(route, relation, unexpected)
    end
  end

  defp validate_tag_values(route, relation, expected_tags) do
    for {k, expected} <- expected_tags do
      actual = Map.get(relation.tags, k)

      if actual != expected do
        Error.invalid_tag_value(route, relation, k, actual, expected)
      end
    end
  end

  #
  # Util fns
  #

  defp route_tag(%Route{type: 0}), do: "tram"
  defp route_tag(%Route{type: 3}), do: "bus"
end