pd.DataFrame(series).plot(kind='bar',figsize=(15,10), subplots=True, layout=(5,2), legend=False, sharey=True)

"""
Explanation: Here are the top 10 most dangerous intersection plotted by year
Note that 2012 and 2016 are not complete.
End of explanation
"""


lat = top10.LATITUDE.values
lon = top10.LONGITUDE.values

glp.dot({'lat': lat, 'lon': lon}, color="r")
glp.inline()

lat

"""
Explanation: Here we see the location of these 10 intersection
End of explanation
"""


top10Injuries = collisions.groupby(['LOCATION'])['NUMBER OF PERSONS INJURED'].sum().sort_values(ascending=False)[:10]
top10Injuries

top10Injuries

top10Killed = collisions.groupby(['LOCATION'])['NUMBER OF PERSONS KILLED'].sum().sort_values(ascending=False)[:11]
top10Killed


def splitLocation(df):
    result = df.copy()
    result['LAT'] = result.index.str.split(',').str.get(0).str.replace('(', '')
    result['LON'] = result.index.str.split(',').str.get(1).str.replace(')', '')
    return result
    

top10KilledDf = splitLocation(top10Killed.to_frame())
top10InjuredDf = splitLocation(top10Injuries.to_frame())

lon = top10KilledDf.LON.astype(float).values
lat = top10KilledDf.LAT.astype(float).values

glp.dot({'lat': lat, 'lon': lon}, color="r")
glp.dot({'lat': top10.LATITUDE.values, 'lon': top10.LONGITUDE.values}, color='g')
glp.dot({'lat': top10InjuredDf.LAT.astype(float).values, 'lon': top10InjuredDf.LON.astype(float).values}, color='b')

glp.inline()

"""
Explanation: That the intersections with the most collions
However how many get injured or killed in these?
End of explanation
"""


def get_intersection_name(e):
    name = collisions[collisions.LOCATION == e.name][['CROSS STREET NAME','ON STREET NAME']].iloc[0]
    return name['ON STREET NAME'] + ' / '+ name['CROSS STREET NAME']
    
top10InjuredDf['NAME'] = top10InjuredDf.apply(get_intersection_name, axis=1, raw=True)
top10KilledDf['NAME'] = top10KilledDf.apply(get_intersection_name, axis=1, raw=True)

top10InjuredDf

top10KilledDf

top10InjuredDf.to_csv('datasets/intersection_top10_injuries.csv', sep=',')
top10KilledDf.to_csv('datasets/intersection_top10_killed.csv', sep=',')

"""
Explanation: Lets save them
End of explanation
"""


# Lets find the average collisions per intersection

means = intersection.mean()
means

print "For each collision %f number of persons gets injured" % (means['NUMBER OF PERSONS INJURED'] / means.LOCATION)

top10InjuredDf


top10Means = top10.mean()
top10InjuredMeans = top10InjuredDf.mean()

top10KilledMean = top10KilledDf.mean()
print "In the intersections with the most collisions, only %f amount of persons where injured\n" % top10Means['NUMBER OF PERSONS INJURED']

print "However looking at the top most intersection with the most injured,\n then we have %f persons injured per collison.\n"\
% (top10InjuredMeans['NUMBER OF PERSONS INJURED'] / top10InjuredMeans['COLLISIONS'])

#print "And lastly looking at the intersections with the most killed people, only %f persons get injured (not including killed) per collision"\
#% (top10KilledMean['NUMBER OF PERSONS INJURED'] / top10KilledMean['COLLISIONS'])


loc_count = collisions.LOCATION.value_counts()


def get_collision_count(e):
    return loc_count[e.name]
    

top10InjuredDf['COLLISIONS'] = top10InjuredDf.copy().apply(get_collision_count, axis=1)

top10KilledDf['COLLISIONS'] = top10KilledDf.copy().apply(get_collision_count, axis=1)

collisions.groupby(['LOCATION']).value_counts()

"""
Explanation: Finding outliers
Finding the intersection with the most injured, relative to the collisions
End of explanation
"""


def calc_collision_inju_ration(e):
    return (e['NUMBER OF PERSONS INJURED'] / e.LOCATION)

intersection[intersection.LOCATION > 20].apply(calc_collision_inju_ration, axis=1, raw=True).sort_values()

collisions[collisions.LOCATION == '(40.6790346, -73.9385077)']

top10['CONTRIBUTING FACTOR VEHICLE 1'].value_counts()

def causesTop(n):
    danger_zone = collisions.LOCATION.value_counts()[n-1:n]
    return collisions[collisions.LOCATION.isin(danger_zone.index)]['CONTRIBUTING FACTOR VEHICLE 1'].value_counts()


series = {}

for i in range(1,10):
    series[i] = causesTop(i)
    
pd.DataFrame(series).plot(kind='bar', figsize=(15,10), subplots=True)

numberTop6 = collisions[collisions.LOCATION.isin(collisions.LOCATION.value_counts()[5:6].index)]

pd.to_datetime(numberTop6.DATE).value_counts().plot(figsize=(15,15))


#pd.Series(range(0,numberTop6['NUMBER OF PERSONS INJURED'].size), index=pd.to_datetime(numberTop6.DATE)).plot(kind='bar',figsize=(15,15))

numberTop6.size

top10

#top10['HOUR'] = top10.TIME.str.split(':').str.get(0).astype('int')
#top1['HOUR'] = top1.TIME.str.split(':').str.get(0).astype('int')
collisions['HOUR'] = collisions.TIME.str.split(':').str.get(0).astype('int')

top10.HOUR.value_counts().sort_index().plot(figsize=(15,10), kind='bar')


top1.HOUR.value_counts().sort_index().plot(figsize=(15,10), kind='bar')

top10.HOUR.value_counts().index

top1 = collisions[collisions.LOCATION.isin(collisions.LOCATION.value_counts()[0:1].index)]

series = {}

for r in collisions['CONTRIBUTING FACTOR VEHICLE 1'].unique():
    series[r] = collisions[collisions['CONTRIBUTING FACTOR VEHICLE 1'] == r].HOUR.value_counts().sort_index()
series['Combined'] = collisions.HOUR.value_counts().sort_index()
pd.DataFrame(series).plot(figsize=(15,100), subplots=True)

collisions['CONTRIBUTING FACTOR VEHICLE 1'].unique()

collisions

collisions.['']

"""
Explanation: Look for some intersections that have a perticular high ration
Meaning where is it perticular dangous to drive.
End of explanation
"""


