#The usual imports
import math
from collections import OrderedDict

from pandas import read_csv
import numpy as np

from pymatgen.util.plotting_utils import get_publication_quality_plot
from monty.string import remove_non_ascii

import prettyplotlib as ppl
from prettyplotlib import brewer2mpl
import matplotlib.pyplot as plt

colors = brewer2mpl.get_map('Set1', 'qualitative', 8).mpl_colors

%matplotlib inline

"""
Explanation: Overview
This is a generalized notebook for computing grade statistics from the Ted Grade Center.
End of explanation
"""


d = read_csv("gc_NANO114_WI15_Ong_fullgc_2015-03-16-15-33-52.csv")
d.columns = [remove_non_ascii(c) for c in d.columns]
d.columns = [c.split("[")[0].strip().strip("\"") for c in d.columns]

"""
Explanation: Load data from exported CSV from Ted Full Grade Center. Some sanitization is performed to remove non-ascii characters and cruft
End of explanation
"""


grade_cutoffs = OrderedDict()
grade_cutoffs["A"] = 0.75
grade_cutoffs["B+"] = 0.5
grade_cutoffs["B"] = -0.25
grade_cutoffs["B-"] = -0.5
grade_cutoffs["C+"] = -0.75
grade_cutoffs["C"] = -1
grade_cutoffs["C-"] = -1.5
grade_cutoffs["F"] = float("-inf")

def bar_plot(dframe, data_key, offset=0):
    """
    Creates a historgram of the results.
    
    Args:
        dframe: DataFrame which is imported from CSV.
        data_key: Specific column to plot
        offset: Allows an offset for each grade. Defaults to 0.
        
    Returns:
        dict of cutoffs, {grade: (lower, upper)}
    """
    data = dframe[data_key]
    d = filter(lambda x: (not np.isnan(x)) and x != 0, list(data))
    heights, bins = np.histogram(d, bins=20, range=(0, 100))
    bins = list(bins)
    bins.pop(-1)
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots(1)
    ppl.bar(ax, bins, heights, width=5, color=colors[0], grid='y')
    plt = get_publication_quality_plot(12, 8, plt)
    plt.xlabel("Score")
    plt.ylabel("Number of students")
    #print len([d for d in data if d > 90])
    mean = data.mean(0)
    sigma = data.std()
    maxy = np.max(heights)
    prev_cutoff = 100
    cutoffs = {}
    grade = ["A", "B+", "B", "B-", "C+", "C", "C-", "F"]
    for grade, cutoff in grade_cutoffs.items():
        if cutoff == float("-inf"):
            cutoff = 0
        else:
            cutoff = max(0, mean + cutoff * sigma) + offset
            plt.plot([cutoff] * 2, [0, maxy], 'k--')
            plt.annotate("%.1f" % cutoff, [cutoff, maxy - 1], fontsize=18, horizontalalignment='left', rotation=45)
        n = len([d for d in data if cutoff <= d < prev_cutoff])
        print "Grade %s (%.1f-%.1f): %d" % (grade, cutoff, prev_cutoff, n)
        plt.annotate(grade, [(cutoff + prev_cutoff) / 2, maxy], fontsize=18, horizontalalignment='center')
        cutoffs[grade] = (cutoff, prev_cutoff)
        prev_cutoff = cutoff
    
    plt.ylim([0, maxy * 1.1])
    plt.annotate("$\mu = %.1f$\n$\sigma = %.1f$\n$max=%.1f$" % (mean, sigma, data.max()), xy=(10, 7), fontsize=30)
    title = data_key.split("[")[0].strip()
    plt.title(title, fontsize=30)
    plt.tight_layout()
    plt.savefig("%s.eps" % title)
    return cutoffs

for c in d.columns:
    if "PS" in c or "Mid-term" in c or "Final" in c:
        if not all(np.isnan(d[c])):
            print c
            bar_plot(d, c)

"""
Explanation: Define lower grade cutoffs in terms of number of standard deviations from mean.
End of explanation
"""


cutoffs = bar_plot(d, "Overall", offset=-2)

def assign_grade(pts):
    for g, c in cutoffs.items():
        if c[0] < pts <= c[1]:
            return g

d["Final_Assigned_Egrade"] = map(assign_grade, d["Overall"])
d.to_csv("Overall grades.csv")

"""
Explanation: Overall grade
Overall points and assign overall grade.
End of explanation
"""


