def user_home_antenna_query(table_name='%(table_name)s', noct_time={'begin':
    19, 'end': 7}):
    """
    Define a monthly home antenna per user, i.e. where does a user have
    the most interactions during that month during a defined
    night time window.

    Inputs
    ------
    table_name : Name of the table the query is supposed to run on,
                 defaulting to '%(table_name)s', i.e. no substitution.
    noct_time : Dictionary holding beginning and end of nocturnal time with
                entries 'begin' and 'end'.

    Output
    ------
    Crosswalk of user_ids and predicted home antenna per month.
    """
    query = """
        SELECT
          user_id,
          antenna_id
        FROM
        (
          SELECT
            user_id,
            antenna_id,
            ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY events DESC)
             as antenna_rank -- ROW_NUMBER instead of RANK (no ties)
          FROM
          (
            SELECT
              user_id,
              antenna_id,
              COUNT(*) as events -- count events per user and antenna
            FROM
            (
              SELECT
                caller_id as user_id,
                antenna_id
              FROM %(table_name)s
              -- infuse nocturnal beginning
              WHERE HOUR(datetime) BETWEEN %(noct_begin)s AND 23
                OR HOUR(datetime) < %(noct_end)s -- infuse nocturnal end
            ) -- get active antennas per user during night time
            GROUP BY user_id, antenna_id
          ) nocturnal
        )
        -- select only 1 antenna per user, the one with the most events
        WHERE antenna_rank = 1
    """
    return query % {'table_name': table_name, 'noct_begin': noct_time[
        'begin'], 'noct_end': noct_time['end']}
