%load_ext autoreload
%autoreload 2
%matplotlib inline

import sqlite3
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

from flight_safety.queries import get_flight_crew_accidents

con = sqlite3.connect('data/avall.db')

flight_crew = get_flight_crew_accidents(con)

"""
Explanation: How does the age of the pilot affect the probability of having an accident?
End of explanation
"""


flight_crew.crew_age.plot(kind='box');

age_bins = np.arange(14, 85, 5)
flight_crew['crew_age'].hist(bins=age_bins, ec='white', grid=False)
plt.xlabel('age')
plt.ylabel('number of accidents');

"""
Explanation: Age distribution of pilots who have had an accident
End of explanation
"""


licenses_by_age_airline = np.array(
    [0, 572, 5199, 12003, 15507, 18337,
     23058, 25882, 24220, 16824, 10184,
     4284, 1766, 787]
)

plt.plot(age_bins[1:], licenses_by_age_airline, 'o-');

"""
Explanation: Number of licenses per age
Active FAA Pilot Certificates Held by Category and Age Group of Holder  according to GAMMA databook
End of explanation
"""


age_group = pd.cut(flight_crew['crew_age'], age_bins)
gby_age = flight_crew['ev_id'].groupby(age_group).count()

accident_rate_age = gby_age / licenses_by_age_airline
accident_rate_age.plot.bar()
plt.ylabel('accidents / licenses')
plt.xlabel('crew age');

"""
Explanation: Accidents per license rate
End of explanation
"""


