7.9 KiB · text History 44bc4f7
defmodule CartosnapApp.Trips.Areas do
  @moduledoc """
  A trip's album split into areas by where the photos were taken: "Kyoto",
  "Osaka", or within a city trip, its neighbourhoods. Worked out from the
  photos each time (no stored state to drift), so they follow the album as
  photos come and go.

  ## How photos are grouped

  Photos closer than a linking distance join one area, and so on along a
  chain (single-linkage, as DBSCAN with one point per cluster). The
  distance follows the trip's spread: a twenty-fifth of the corner-to-corner
  span of all its photos, kept between 300 m and 20 km. A walking tour of a
  city splits by neighbourhood; a road trip by town.

  To stay fast on big albums, photos are bucketed into a grid of cells one
  linking distance wide: photos in one cell always group (they're within
  about 1.4 times the distance), and neighbouring cells join when any pair
  across them is within it.

  ## Names

  An area is named by reverse geocoding its centre (`CartosnapApp.Geocoder.reverse/3`),
  at town scale or, for areas within a city, neighbourhood scale. Names are
  kept in `place_names`, keyed by scale and centre to about a kilometre, so
  each place is asked about once. Until a name is known, an area is "Area 2".
  """

  import Ecto.Query

  alias CartosnapApp.Geocoder
  alias CartosnapApp.Photos.Photo
  alias CartosnapApp.Repo

  @min_link 300
  @max_link 20_000
  @spread_fraction 25
  @neighbourhood_below 2_500
  @earth_radius 6_371_000
  @metres_per_degree 111_320

  @doc """
  The areas of these photos, in the order they were first visited:

      [%{id: "1", index: 1, name: nil, lat: _, lon: _,
         bounds: {south, west, north, east}, radius: metres,
         photo_ids: MapSet, count: n, scale: :town, key: "town:35.01,135.77"}]

  Photos without a position belong to none. Fewer than two areas is no
  split at all, so that's `[]`.
  """
  def split(photos) do
    points =
      for %Photo{} = photo <- photos, {lat, lon} <- [Photo.lat_lon(photo)] do
        %{id: photo.id, lat: lat, lon: lon, date: photo.date}
      end

    case points do
      [_, _ | _] ->
        link = link_distance(points)

        points
        |> group(link)
        |> case do
          [_, _ | _] = groups -> describe(groups, scale(link))
          _ -> []
        end

      _ ->
        []
    end
  end

  @doc "The linking distance for these points, in metres."
  def link_distance(points) do
    {lats, lons} = points |> Enum.map(&{&1.lat, &1.lon}) |> Enum.unzip()
    span = distance({Enum.min(lats), Enum.min(lons)}, {Enum.max(lats), Enum.max(lons)})
    (span / @spread_fraction) |> max(@min_link) |> min(@max_link)
  end

  defp scale(link) when link < @neighbourhood_below, do: :neighbourhood
  defp scale(_link), do: :town

  # Points into groups of points, by grid cell then by neighbouring cells.
  defp group(points, link) do
    mean_lat = Enum.sum_by(points, & &1.lat) / length(points)
    cell_lat = link / @metres_per_degree
    cell_lon = link / (@metres_per_degree * max(:math.cos(radians(mean_lat)), 0.1))

    cells =
      Enum.group_by(points, fn p -> {floor(p.lat / cell_lat), floor(p.lon / cell_lon)} end)

    parents =
      Enum.reduce(cells, Map.new(cells, fn {cell, _} -> {cell, cell} end), fn {{r, c} = cell,
                                                                               members},
                                                                              parents ->
        # Each pair of neighbouring cells once: the four ahead of this one.
        Enum.reduce([{r, c + 1}, {r + 1, c - 1}, {r + 1, c}, {r + 1, c + 1}], parents, fn next,
                                                                                          parents ->
          with others when is_list(others) <- Map.get(cells, next),
               true <- near?(members, others, link) do
            union(parents, cell, next)
          else
            _ -> parents
          end
        end)
      end)

    cells
    |> Enum.group_by(fn {cell, _} -> root(parents, cell) end, fn {_, members} -> members end)
    |> Enum.map(fn {_root, lists} -> List.flatten(lists) end)
  end

  defp near?(as, bs, link),
    do:
      Enum.any?(as, fn a ->
        Enum.any?(bs, &(distance({a.lat, a.lon}, {&1.lat, &1.lon}) <= link))
      end)

  defp root(parents, cell) do
    case Map.fetch!(parents, cell) do
      ^cell -> cell
      parent -> root(parents, parent)
    end
  end

  defp union(parents, a, b) do
    {ra, rb} = {root(parents, a), root(parents, b)}
    if ra == rb, do: parents, else: Map.put(parents, ra, rb)
  end

  defp describe(groups, scale) do
    groups
    |> Enum.sort_by(fn members -> {first_date(members), length(members)} end)
    |> Enum.with_index(1)
    |> Enum.map(fn {members, index} ->
      lat = Enum.sum_by(members, & &1.lat) / length(members)
      lon = Enum.sum_by(members, & &1.lon) / length(members)
      {lats, lons} = members |> Enum.map(&{&1.lat, &1.lon}) |> Enum.unzip()

      %{
        id: Integer.to_string(index),
        index: index,
        name: nil,
        lat: lat,
        lon: lon,
        bounds: {Enum.min(lats), Enum.min(lons), Enum.max(lats), Enum.max(lons)},
        radius: members |> Enum.map(&distance({lat, lon}, {&1.lat, &1.lon})) |> Enum.max(),
        photo_ids: MapSet.new(members, & &1.id),
        count: length(members),
        scale: scale,
        key: "#{scale}:#{Float.round(lat, 2)},#{Float.round(lon, 2)}"
      }
    end)
  end

  # Undated photos sort last; DateTime compares by struct, so by unix time.
  defp first_date(members) do
    members
    |> Enum.map(& &1.date)
    |> Enum.reject(&is_nil/1)
    |> Enum.map(&DateTime.to_unix/1)
    |> Enum.min(fn -> :infinity end)
  end

  ## Names

  @doc """
  Names the areas from what's already known, numbering any unknown, and
  telling apart areas that share a name ("Tokyo", "Tokyo (2)").
  """
  def name(areas, names) do
    {named, _seen} =
      Enum.map_reduce(areas, %{}, fn area, seen ->
        base = Map.get(names, area.key) || "Area #{area.index}"
        n = Map.get(seen, base, 0) + 1
        name = if n == 1, do: base, else: "#{base} (#{n})"
        {%{area | name: name}, Map.put(seen, base, n)}
      end)

    named
  end

  @doc "The stored names for these areas' places: `%{key => name}` (unknown places left out)."
  def known_names([]), do: %{}

  def known_names(areas) do
    keys = Enum.map(areas, & &1.key)

    from(n in "place_names", where: n.key in ^keys, select: {n.key, n.name})
    |> Repo.all()
    |> Map.new()
  end

  @doc "The areas whose place hasn't been looked up yet."
  def unnamed(areas, names), do: Enum.reject(areas, &Map.has_key?(names, &1.key))

  @doc """
  Looks up the places of these areas and stores what's found, returning
  `%{key => name}`. A place with no name is stored as nil, so it isn't
  asked about again; one whose lookup failed isn't stored, so it is.
  Asks two at a time, to go easy on the public geocoder.
  """
  def look_up_names(areas) do
    found =
      areas
      |> Enum.uniq_by(& &1.key)
      |> Task.async_stream(
        fn area -> {area.key, Geocoder.reverse(area.lat, area.lon, scale: area.scale)} end,
        max_concurrency: 2,
        timeout: 30_000,
        on_timeout: :kill_task
      )
      |> Enum.flat_map(fn
        {:ok, {key, {:ok, name}}} -> [{key, name}]
        _ -> []
      end)

    now = NaiveDateTime.utc_now(:second)

    Repo.insert_all(
      "place_names",
      Enum.map(found, fn {key, name} -> %{key: key, name: name, inserted_at: now} end),
      on_conflict: :nothing
    )

    Map.new(found)
  end

  ## Geometry

  @doc "Metres between two `{lat, lon}`s (haversine)."
  def distance({lat1, lon1}, {lat2, lon2}) do
    dlat = radians(lat2 - lat1)
    dlon = radians(lon2 - lon1)

    a =
      :math.pow(:math.sin(dlat / 2), 2) +
        :math.cos(radians(lat1)) * :math.cos(radians(lat2)) * :math.pow(:math.sin(dlon / 2), 2)

    2 * @earth_radius * :math.asin(min(1.0, :math.sqrt(a)))
  end

  defp radians(degrees), do: degrees * :math.pi() / 180
end