import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import itemfreq


year=2012 #2012
doy=138  #138
if year>2000: prefix="epi"
else: prefix="eph"

from matplotlib import cm
mycolors = [ cm.jet(x) for x in np.linspace(0,1, 13 ) ][1:]
mycolors=["deepskyblue","mediumslateblue","steelblue","blue","orange","tomato","indianred","red","lightgreen","lawngreen","forestgreen","g","k"]

coinc=np.loadtxt("/data/missions/soho/costep/level2/pha/%s/%s%s%03d.pl2"%(year,prefix,str(year)[-2:],doy),usecols=(1,),unpack=True)
only_stopping="False"

if only_stopping=="True": coinc=coinc[coinc!=12]

#coinc=coinc[:100]
total_counts=len(coinc)
analyse=itemfreq(coinc)

labels=analyse[:,0]
for q in range(len(labels)):   labels[q]=str(int(labels[q]))

counts=analyse[:,1]
plt.figure()
plt.gca().axis('equal')
if only_stopping: plt.title("Stopping coincidences on day %s-%03d (%i in total)"%(year,doy,total_counts))
else: plt.title("Coincidences on day %s-%03d (%i in total)"%(year,doy,total_counts))
tcolors=[]
for q in labels: tcolors.append(mycolors[int(q)])
patches, texts, autotexts =plt.pie(counts,labels=labels,autopct='%1.0f%%',colors=tcolors,startangle=90,radius=0.9)
for q in range(len(texts)): 
  tcoinc= (texts[q].get_text().split(".")[0])
  if q==0:  texts[q].set_text("Coincidence %s"%texts[q].get_text().split(".")[0])
  else:  texts[q].set_text("%s"%texts[q].get_text().split(".")[0])
  texts[q].set_color(tcolors[q])
for q in range(len(autotexts)):
  autotexts[q].set_color("w")
#texts[0].text("%i"%1)



plt.pie([1],radius=0.35,colors=["w"])

if only_stopping=="True": 
  counts=[np.sum(counts[labels<4]) , np.sum(counts[(4<=labels)*(labels<8)]) , np.sum(counts[(8<=labels)*(labels<12)]) ]
  labels=["electron","proton","helium"]
  colors=["b","r","g"]
else:
  counts=[np.sum(counts[labels<4]) , np.sum(counts[(4<=labels)*(labels<8)]) , np.sum(counts[(8<=labels)*(labels<12)]) , counts[labels==12][0] ]
  labels=["electron","proton","helium","integral"]
  colors=["b","r","g","k"]


patches, texts, autotexts =plt.pie(counts,startangle=90,radius=0.3,autopct='%1.0f%%',colors=colors)
for q in range(len(autotexts)):
  autotexts[q].set_color("w")
plt.show()
