import pandas
import numpy
from folding_group import FoldingGroupClassifier
from rep.data import LabeledDataStorage
from rep.report import ClassificationReport
from rep.report.metrics import RocAuc

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_curve, roc_auc_score

from utils import get_N_B_events, get_events_number, get_events_statistics

"""
Explanation: Import
End of explanation
"""


import root_numpy
data_nan = pandas.DataFrame(root_numpy.root2array('datasets/tracks.root', 'tracks'))

data_nan.head()

event_id_column = 'event_id'
event_id = data_nan.run.apply(str) + '_' + data_nan.event.apply(str)
data_nan[event_id_column] = numpy.unique(event_id, return_inverse=True)[1]

get_events_statistics(data_nan)

get_N_B_events()

"""
Explanation: Reading initial data
End of explanation
"""


data = data_nan.dropna()
len(data_nan), len(data), get_events_statistics(data)

"""
Explanation: Remove rows with NAN from data
End of explanation
"""


# add different between max pt in event and pt for each track
def add_diff_pt(data):
    max_pt = group_max(data[event_id_column].values.astype(str), data.partPt.values)
    data.loc[:, 'diff_pt'] = max_pt - data['partPt'].values

# max is computing max over tracks in the same event for saome data
def group_max(groups, data):
    # computing unique integer id for each group
    assert len(groups) == len(data)
    _, event_id = numpy.unique(groups, return_inverse=True)
    max_over_event = numpy.zeros(max(event_id) + 1) - numpy.inf
    numpy.maximum.at(max_over_event, event_id, data)
    return max_over_event[event_id]

# add diff pt
add_diff_pt(data)
# add cos(diff_phi)
data.loc[:, 'cos_diff_phi'] = numpy.cos(data.diff_phi.values)

"""
Explanation: Add diff_pt and cos(diff_phi)
End of explanation
"""


from itertools import combinations
PIDs = {'k': data.PIDNNk.values,
        'e': data.PIDNNe.values,
        'mu': data.PIDNNm.values,
       }
for (pid_name1, pid_values1), (pid_name2, pid_values2) in combinations(PIDs.items(), 2):
    data.loc[:, 'max_PID_{}_{}'.format(pid_name1, pid_name2)] = numpy.maximum(pid_values1, pid_values2)
    data.loc[:, 'sum_PID_{}_{}'.format(pid_name1, pid_name2)] = pid_values1 + pid_values2

"""
Explanation: Add max, sum among PIDs
End of explanation
"""


data.loc[:, 'label'] = (data.signB.values * data.signTrack.values > 0) * 1

','.join(data.columns)

"""
Explanation: define label = signB * signTrack

if > 0 (same sign) - label 1
if < 0 (different sign) - label 0
End of explanation
"""


initial_cut = '(ghostProb < 0.4)'
data = data.query(initial_cut)
ss_selection = (data.IPs.values < 3) * (abs(data.diff_eta.values) < 0.6) * (abs(data.diff_phi.values) < 0.825)
data = data[ss_selection]

get_events_statistics(data)

"""
Explanation: Apply ghost prob cut, leave  Same Side (SS) tracks
End of explanation
"""


threshold_kaon = 0.
threshold_muon = 0.
threshold_electron = 0.
threshold_pion = 0.
threshold_proton = 0.
cut_pid = " ( (PIDNNk > {trk}) | (PIDNNm > {trm}) | (PIDNNe > {tre}) | (PIDNNpi > {trpi}) | (PIDNNp > {trp})) "
cut_pid = cut_pid.format(trk=threshold_kaon, trm=threshold_muon, tre=threshold_electron, trpi=threshold_pion,
                         trp=threshold_proton)
    
data = data.query(cut_pid)

get_events_statistics(data)

"""
Explanation: Leave not muons, kaons, electrons, pions, protons
End of explanation
"""


N_B_passed = float(get_events_number(data))
tagging_efficiency = N_B_passed / get_N_B_events()
tagging_efficiency_delta = sqrt(N_B_passed) / get_N_B_events()
tagging_efficiency, tagging_efficiency_delta

hist(data.diff_pt.values, bins=100)
pass

"""
Explanation: Calculating tagging efficiency ($\epsilon_{tag}$)
$$N (\text{passed selection}) = \sum_{\text{passed selection}} sw_i$$
$$N (\text{all events}) = \sum_{\text{all events}} sw_i,$$
where $sw_i$ - sPLot weight (sWeight for signal)
$$\epsilon_{tag} = \frac{N (\text{passed selection})} {N (\text{all events})}$$
$$\Delta\epsilon_{tag} = \frac{\sqrt{N (\text{passed selection})}} {N (\text{all events})}$$
End of explanation
"""


_, take_indices = numpy.unique(data[event_id_column], return_index=True)

figure(figsize=[15, 5])

subplot(1, 2, 1)
hist(data.Bmass.values[take_indices], bins=100)
title('B mass hist')
xlabel('mass')

subplot(1, 2, 2)
hist(data.N_sig_sw.values[take_indices], bins=100, normed=True)
title('sWeights hist')
xlabel('signal sWeights')
plt.savefig('img/Bmass_SS.png' , format='png')

"""
Explanation: Choose most probable B-events
End of explanation
"""


sweight_threshold = 1.
data_sw_passed = data[data.N_sig_sw > sweight_threshold]
data_sw_not_passed = data[data.N_sig_sw <= sweight_threshold]
get_events_statistics(data_sw_passed)

_, take_indices = numpy.unique(data_sw_passed[event_id_column], return_index=True)

figure(figsize=[15, 5])
subplot(1, 2, 1)
hist(data_sw_passed.Bmass.values[take_indices], bins=100)
title('B mass hist for sWeight > 1 selection')
xlabel('mass')

subplot(1, 2, 2)
hist(data_sw_passed.N_sig_sw.values[take_indices], bins=100, normed=True)
title('sWeights hist for sWeight > 1 selection')
xlabel('signal sWeights')
plt.savefig('img/Bmass_selected_SS.png' , format='png')

hist(data_sw_passed.diff_pt.values, bins=100)
pass

"""
Explanation: Define B-like events for training
Events with low sWeight still will be used only to test quality.
End of explanation
"""


features = list(set(data.columns) - {'index', 'run', 'event', 'i', 'signB', 'signTrack', 'N_sig_sw', 'Bmass', 'mult', 
                                     'PIDNNp', 'PIDNNpi', 'label', 'thetaMin', 'Dist_phi', event_id_column, 
                                     'mu_cut', 'e_cut', 'K_cut', 'ID', 'diff_phi'})
features

"""
Explanation: Main idea:
find tracks, which can help reconstruct the sign of B if you know track sign.
label = signB * signTrack
* the highest output means that this is same sign B as track
* the lowest output means that this is opposite sign B than track
Define features
End of explanation
"""


figure(figsize=[15, 16])
bins = 60
step = 3
for i, (feature1, feature2) in enumerate(combinations(['PIDNNk', 'PIDNNm', 'PIDNNe', 'PIDNNp', 'PIDNNpi'], 2)):
    subplot(4, 3, i + 1)
    Z, (x, y) = numpy.histogramdd(data_sw_passed[[feature1, feature2]].values, bins=bins, range=([0, 1], [0, 1]))
    pcolor(log(Z), vmin=0)
    xlabel(feature1)
    ylabel(feature2)
    xticks(arange(bins, step), x[::step]), yticks(arange(bins, step), y[::step])
plt.savefig('img/PID_selected_SS.png' , format='png')

"""
Explanation: PID pairs scatters
End of explanation
"""


hist(data_sw_passed.diff_pt.values, bins=60, normed=True)
pass

"""
Explanation: pt
End of explanation
"""


_, n_tracks = numpy.unique(data_sw_passed[event_id_column], return_counts=True)
hist(n_tracks, bins=100)    
title('Number of tracks')
plt.savefig('img/tracks_number_SS.png' , format='png')

"""
Explanation: count of tracks
End of explanation
"""


figure(figsize=[15, 4])
for i, column in enumerate(['PIDNNm', 'PIDNNe', 'PIDNNk']):
    subplot(1, 3, i + 1)
    hist(data_sw_passed[column].values, bins=60, range=(0, 1), label=column)
    legend()

"""
Explanation: PIDs histograms
End of explanation
"""


from hep_ml.decisiontrain import DecisionTrainClassifier
from hep_ml.losses import LogLossFunction
from rep.estimators import SklearnClassifier

data_sw_passed_lds = LabeledDataStorage(data_sw_passed, data_sw_passed.label, data_sw_passed.N_sig_sw.values)

"""
Explanation: Train to distinguish same sign vs opposite sign
End of explanation
"""


tt_base = DecisionTrainClassifier(learning_rate=0.02, n_estimators=3000, depth=6,
                                  max_features=15, loss=LogLossFunction(regularization=100))
tt_folding = FoldingGroupClassifier(SklearnClassifier(tt_base), n_folds=2, random_state=11, 
                                    train_features=features, group_feature=event_id_column)
%time tt_folding.fit_lds(data_sw_passed_lds)
pass

import cPickle
with open('models/dt_SS.pkl', 'w') as f:
    cPickle.dump(tt_folding, f)

comparison_report = ClassificationReport({'tt': tt_folding}, data_sw_passed_lds)

comparison_report.compute_metric(RocAuc())

comparison_report.roc()

lc = comparison_report.learning_curve(RocAuc(), steps=100)

lc

for est in tt_folding.estimators:
    est.estimators = est.estimators[:2000]

comparison_report.feature_importance()

"""
Explanation: DT
End of explanation
"""


from utils import get_result_with_bootstrap_for_given_part

models = []

models.append(get_result_with_bootstrap_for_given_part(tagging_efficiency, tagging_efficiency_delta, tt_folding, 
                                                      [data_sw_passed, data_sw_not_passed], 'tt-iso', logistic=False))

models.append(get_result_with_bootstrap_for_given_part(tagging_efficiency, tagging_efficiency_delta, tt_folding, 
                                                      [data_sw_passed, data_sw_not_passed], 'tt-log', logistic=True))

"""
Explanation: Calibration
End of explanation
"""


pandas.set_option('display.precision', 8)
result = pandas.concat(models)
result.index = result.name
result.drop('name', axis=1)

"""
Explanation: Comparison table of different models
End of explanation
"""


from utils import prepare_B_data_for_given_part

Bdata_prepared = prepare_B_data_for_given_part(tt_folding, [data_sw_passed, data_sw_not_passed], logistic=True)

Bdata_prepared.to_csv('models/Bdata_tracks_SS.csv', header=True, index=False)

"""
Explanation: Implementing best tracking
End of explanation
"""


