text: # -*- coding: utf-8 -*-
  #!/usr/bin/env python
  
  """
  Objective:
  Calculate the average travel time for each 20-minute time window.
  
  """
  
  # import necessary modules
  import math
  from datetime import datetime, timedelta
  import pandas as pd
  from common import utils
  
  
  def avgTravelTime(in_file_name):
  
      # Step 1: Load trajectories
      fr = open(in_file_name, 'r')
      fr.readline()  # skip the header
      traj_data = fr.readlines()
      fr.close()
  
      # Step 2: Create a dictionary to store travel time for each route per time window
      travel_times = {}  # key: route_id. Value is also a dictionary of which key is the start time for the time window and value is a list of travel times
      for i in range(len(traj_data)):
          each_traj = traj_data[i].replace('"', '').split(',')
          intersection_id = each_traj[0]
          tollgate_id = each_traj[1]
  
          route_id = intersection_id + '-' + tollgate_id
          if route_id not in travel_times.keys():
              travel_times[route_id] = {}
  
          trace_start_time = each_traj[3]
          trace_start_time = datetime.strptime(trace_start_time, "%Y-%m-%d %H:%M:%S")
          time_window_minute = math.floor(trace_start_time.minute / 20) * 20
          start_time_window = datetime(trace_start_time.year, trace_start_time.month, trace_start_time.day,
                                       trace_start_time.hour, time_window_minute, 0)
          tt = float(each_traj[-1])  # travel time
  
          if start_time_window not in travel_times[route_id].keys():
              travel_times[route_id][start_time_window] = [tt]
          else:
              travel_times[route_id][start_time_window].append(tt)
  
      # Step 3: Calculate average travel time for each route per time window
      result = []
      result.append(['intersection_id', 'tollgate_id',
                     'time_window_start', 'time_window_end',
                     'avg_travel_time'])
      for route in travel_times.keys():
          route_time_windows = list(travel_times[route].keys())
          route_time_windows.sort()
          for time_window_start in route_time_windows:
              time_window_end = time_window_start + timedelta(minutes=20)
              tt_set = travel_times[route][time_window_start]
              avg_tt = round(sum(tt_set) / float(len(tt_set)), 2)
              result.append([route.split('-')[0],
                             route.split('-')[1],
                             str(time_window_start),
                             str(time_window_end),
                             avg_tt])
  
      return result
  
  
  def avgVolume(in_file):
  
      # Step 1: Load volume data
      fr = open(in_file, 'r')
      fr.readline()  # skip the header
      vol_data = fr.readlines()
      fr.close()
  
      # Step 2: Create a dictionary to caculate and store volume per time window
      volumes = {}  # key: time window value: dictionary
      for i in range(len(vol_data)):
          each_pass = vol_data[i].replace('"', '').split(',')
          tollgate_id = each_pass[1]
          direction = each_pass[2]
  
          pass_time = each_pass[0]
          pass_time = datetime.strptime(pass_time, "%Y-%m-%d %H:%M:%S")
          time_window_minute = int(math.floor(pass_time.minute / 20) * 20)
          #print pass_time
          start_time_window = datetime(pass_time.year, pass_time.month, pass_time.day,
                                       pass_time.hour, time_window_minute, 0)
  
          if start_time_window not in volumes:
              volumes[start_time_window] = {}
          if tollgate_id not in volumes[start_time_window]:
              volumes[start_time_window][tollgate_id] = {}
          if direction not in volumes[start_time_window][tollgate_id]:
              volumes[start_time_window][tollgate_id][direction] = 1
          else:
              volumes[start_time_window][tollgate_id][direction] += 1
  
      # Step 3: format output for tollgate and direction per time window
      time_windows = list(volumes.keys())
      time_windows.sort()
      results = [['tollgate_id', 'time_window_start', 'time_window_end', 'direction', 'volume']]
      for time_window_start in time_windows:
          time_window_end = time_window_start + timedelta(minutes=20)
          for tollgate_id in volumes[time_window_start]:
              for direction in volumes[time_window_start][tollgate_id]:
                  results.append([
                      tollgate_id,
                      time_window_start,
                      time_window_end,
                      direction,
                      volumes[time_window_start][tollgate_id][direction]
                  ])
  
      return results
  