# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Chapter3Model1.py
# Created on: 2014-04-22 21:59:31.00000
#   (generated by ArcGIS/ModelBuilder)
# Description: 
# Adjusted by Silas Toms
# 2014 04 23
# ---------------------------------------------------------------------------

# Import arcpy module
import arcpy
import csv


# Local variables:
Bus_Stops = r"C:\Projects\SanFrancisco.gdb\SanFrancisco\Bus_Stops"
CensusBlocks2010 = r"C:\Projects\SanFrancisco.gdb\SanFrancisco\CensusBlocks2010"
Inbound71 = r"C:\Projects\SanFrancisco.gdb\Chapter3Results\Inbound71"
Inbound71_400ft_buffer = r"C:\Projects\SanFrancisco.gdb\Chapter3Results\Inbound71_400ft_buffer"
Intersect71Census = r"C:\Projects\SanFrancisco.gdb\Chapter3Results\Intersect71Census"

# Process: Select
arcpy.Select_analysis(Bus_Stops, 
                      Inbound71, 
                      "NAME = '71 IB' AND BUS_SIGNAG = 'Ferry Plaza'")
 
# Process: Buffer
arcpy.Buffer_analysis(Inbound71, 
                      Inbound71_400ft_buffer, 
                      "400 Feet", "FULL", "ROUND", "NONE", "")
 
# Process: Intersect
arcpy.Intersect_analysis("{0} #;{1} #".format(Inbound71_400ft_buffer,CensusBlocks2010), 
                         Intersect71Census, "ALL", "", "INPUT")

dataDictionary = {}

with arcpy.da.SearchCursor(Intersect71Census, ["STOPID","POP10"]) as cursor:
    for row in cursor:
        busStopID = row[0]
        pop10 = row[1]
        if busStopID not in dataDictionary.keys():
            dataDictionary[busStopID] = [pop10]
        else:
            dataDictionary[busStopID].append(pop10)


with open(r'C:\Projects\Output\Averages.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',')
    for busStopID in dataDictionary.keys():
        popList = dataDictionary[busStopID]
        averagePop = sum(popList)/len(popList)
        data = [busStopID, averagePop]
        csvwriter.writerow(data)

print "Data Analysis Complete"
