from __future__ import unicode_literals
import numpy as np
from astropy.io import fits
from scipy import signal
from pylab import * # This program requires the matplotlib python library for the plots.
import math
import matplotlib
#matplotlib.rcParams['text.usetex'] = True
#matplotlib.rcParams['text.latex.unicode'] = True
import matplotlib.pyplot as plt
from astropy.table import Table
import matplotlib.path as mpath
#from matplotlib import rc



def custom_marker():
    # u = np.array([  [2.444,7.553],
    #                 [0.513,7.046],
    #                 [-1.243,5.433],
    #                 [-2.353,2.975],
    #                 [-2.578,0.092],
    #                 [-2.075,-1.795],
    #                 [-0.336,-2.870],
    #                 [2.609,-2.016]  ])
    # u[:,0] -= 0.098
    # codes = [1] + [2]*(len(u)-2) + [2] 
    # u = np.append(u, -u[::-1], axis=0)
    # codes += codes

    star1 = mpath.Path.unit_regular_star(5, innerCircle=0.4)
    star2 = mpath.Path.unit_regular_star(5, innerCircle=0.4)
    star3 = mpath.Path.unit_regular_star(5, innerCircle=0.4)

    # star = mpath.Path.unit_regular_asterisk(5)
    # circle = mpath.Path.unit_circle()
    # verts = np.concatenate([star2.vertices[::-1, ...]*1.5, star.vertices, star3.vertices*-0.5])
    factor1 = 5.0
    factor2 = 2.0
    factor3 = 1.0
    verts = np.concatenate([star1.vertices[::-1,...] * factor1, star2.vertices * factor2, star3.vertices[::-1,...] * factor3])
    codes = np.concatenate([star1.codes, star2.codes, star3.codes])
    
    return mpath.Path(verts, codes)

# use to make matplotlib-old like style
plt.style.use('classic')

font = {'family': 'serif',
        'color':  'black',
        'weight': 'normal',
        'size': 16,
        }


imbh_lit = [
    ['587742610270847183',70e3,6.5e8],
    ['587729160057127189',107e3,1.32e9],
    ['587739720846934480',111e3,1.74e9],
    ['587725818021871671',152e3,2.36e9],
    ['587724240687792193',202e3,7.26e8],

    
    
    ]

imbh_lit = np.array(imbh_lit)
M_sph_arr =[]
M_bh_arr =[]

M_sph_arr_J =[]
M_bh_arr_J =[]

M_sph_arr_GS13_sc =[]
M_bh_arr_GS13_sc =[]

M_sph_arr_GS13_s =[]
M_bh_arr_GS13_s =[]

M_sph_arr_imbh =[]
M_bh_arr_imbh =[]

M_sph_arr_imbh_other =[]
M_bh_arr_imbh_other =[]


M_sph_arr_imbh_confirmed =[]
M_sph_arr_imbh_confirmed_err =[]
M_bh_arr_imbh_confirmed =[]

x_borders = np.array([1e9, 1e11])
line_1 = 10**(2.22*np.log(x_borders/2e10)/math.log(10)+7.89)
x_borders2 = np.array([2e10, 1e12])
line_2 = 10**(0.97*np.log(x_borders2/3e11)/math.log(10)+9.27)

f = open('table2.dat')
for content in f.readlines():
    splitted_arr = content.split('|')
    M_sph_arr.append(float(splitted_arr[9])*1e9)
    M_bh_arr.append(float(splitted_arr[2])*1e5)
f.close()


f = open('scott13')
for content in f.readlines():
    splitted_arr = content.split('&')
    M_bh_col =  splitted_arr[3]
    M_bh_col_arr = M_bh_col.split('$')
    M_sph_col =  splitted_arr[6]
    M_sph_col_arr = M_sph_col.split('$')
    M_sph_arr_GS13_s.append(float(M_sph_col_arr[0])*1e10)
    M_bh_arr_GS13_s.append(float(M_bh_col_arr[0])*1e8)
f.close()



hdulist = fits.open('asu(2).fit')

data = hdulist[1].data

'''
for content in f.readlines():
    splitted_arr = content.split(' ')
    print splitted_arr[15]
    M_bh_arr_J.append(10**float(splitted_arr[2]))
    #M_sph_arr_J.append(float(splitted_arr[16]))
f.close()
'''
M_sun_K = 3.3
M_sun_r = 4.76
f = open('decomp_res_v2')
for content in f.readlines():
    splitted_arr = content.split(',')
    M_sun = M_sun_K
    if 'R' in splitted_arr[8]:
        M_sun = M_sun_r
    Luminosity = 10**(0.4*(M_sun - float(splitted_arr[1])-float(splitted_arr[7])))
    Mass = Luminosity * float(splitted_arr[4])
    print Mass
    if int(splitted_arr[6]) is not 1:
        M_sph_arr_imbh.append(Mass)
        M_bh_arr_imbh.append(float(splitted_arr[5]))
        '''
        text(Mass, float(splitted_arr[5]), splitted_arr[9],
        verticalalignment='bottom', horizontalalignment='left',
        color='red', fontsize=5)
        '''
    else:
        M_sph_arr_imbh_confirmed.append(Mass)
        M_bh_arr_imbh_confirmed.append(float(splitted_arr[5]))
        M_sph_arr_imbh_confirmed_err.append(Mass*float(splitted_arr[10]))
        '''
        text(Mass, float(splitted_arr[5]), splitted_arr[9],
        verticalalignment='bottom', horizontalalignment='left',
        color='green', fontsize=5)
        '''
f.close()


f = open('decomp_res')
for content in f.readlines():
    splitted_arr = content.split(',')
    M_sun = M_sun_K
    if 'R' in splitted_arr[8]:
        M_sun = M_sun_r
    Luminosity = 10**(0.4*(M_sun - float(splitted_arr[1])-float(splitted_arr[7])))
    Mass = Luminosity * float(splitted_arr[4])
    print Mass
    M_sph_arr_imbh_other.append(Mass)
    M_bh_arr_imbh_other.append(float(splitted_arr[5]))

f.close()

t_LTR = Table.read('../../data/mbh_data.txt', format='ascii')

print t_LTR['MBH'].shape
t_UCD = t_LTR[t_LTR['objtype'] == 'UCD']
t_cE = t_LTR[t_LTR['objtype'] == 'cE']
t_other = t_LTR[(t_LTR['objtype'] != 'cE') & (t_LTR['objtype'] != 'UCD')]


X_arr = np.array(t_LTR['Mstar'])
Y_arr = np.array(t_LTR['MBH'])
#ltr, = plt.quiver(X_arr, Y_arr,X_arr*0, Y_arr/4)

lolims_UCD = np.zeros(shape=len(t_UCD), dtype=bool)
lolims_UCD[t_UCD['errMBHp'] == 0.0] = True
err_m = t_UCD['errMBHm']
err_m[lolims_UCD == True] = t_UCD['MBH'][lolims_UCD == True] * 0.1
plt.errorbar(t_UCD['Mstar'], t_UCD['MBH'], xerr=t_UCD['errMstar'], yerr=[err_m,t_UCD['errMBHp']],linestyle='none',uplims=lolims_UCD, color='magenta')
lit_UCD, = plt.loglog(t_UCD['Mstar'], t_UCD['MBH'], linestyle='none',marker='o', color='magenta', markeredgewidth=0.0, markersize=5)

lolims_cE = np.zeros(shape=len(t_cE), dtype=bool)
lolims_cE[t_cE['errMBHp'] == 0.0] = True
plt.errorbar(t_cE['Mstar'], t_cE['MBH'], xerr=t_cE['errMstar'], yerr=[t_cE['errMBHm'],t_cE['errMBHp']],linestyle='none',uplims=lolims_cE, color='gray')
lit_cE, = plt.loglog(t_cE['Mstar'], t_cE['MBH'], linestyle='none',marker='o', color='gray', markeredgewidth=0.0, markersize=5)
shifts = {'NGC5102':{'dx':1.2, 'dy':0.8}, 'NGC5206':{'dx':1.2, 'dy':0.70}, 'NGC4395':{'dx':0.45, 'dy':1.3}, 'NGC205':{'dx':1.2, 'dy':0.75}, 'NGC404':{'dx':0.22, 'dy':1.05},
          'Messier32':{'dx':1.15, 'dy':0.75},'NGC4486B':{'dx':1.15, 'dy':0.75},'M32':{'dx':1.15, 'dy':0.75}}

for itm in t_cE:
    (dx, dy) = (1. , 1.)
    if itm['Object'] in shifts.keys():
        (dx, dy) = (shifts[itm['Object']]['dx'], shifts[itm['Object']]['dy'])
    plt.text(itm['Mstar']*dx,  itm['MBH']*dy,  itm['Object'],
    verticalalignment='bottom', horizontalalignment='left',
    color='gray', fontsize=10)




lolims_other = np.zeros(shape=len(t_other), dtype=bool)
lolims_other[t_other['errMBHm'] == 0] = True

lolims_other[( t_other['MBH'] / (t_other['errMBHm'] + 1.0) < 1.2)] = True

err_m = t_other['errMstar'].copy()
err_m[t_other['errMstar'] == 0] = t_other['Mstar'][t_other['errMstar'] == 0] * 0.2
xuplims = np.zeros(shape=len(t_other), dtype=bool)
xuplims[t_other['errMstar'] == 0] = True
bh_m_err = t_other['errMBHm']
bh_m_err_p = t_other['errMBHp']

bh_m_err[lolims_other == True] = t_other['MBH'][lolims_other == True] * 0.4
bh_m_err_p[lolims_other == True] = t_other['MBH'][lolims_other == True] * 0

print xuplims, lolims_other

plt.errorbar(t_other['Mstar'], t_other['MBH'], xerr=err_m, yerr=[bh_m_err,bh_m_err_p],linestyle='none',uplims=lolims_other,xuplims=xuplims, color='peru')
lit_other, = plt.loglog(t_other['Mstar'], t_other['MBH'], linestyle='none',marker='o', color='peru', markeredgewidth=0.0, markersize=5)

for itm in t_other:
    (dx, dy) = (1. , 1.)
    if itm['Object'] in shifts.keys():
        (dx, dy) = (shifts[itm['Object']]['dx'], shifts[itm['Object']]['dy'])
    plt.text(itm['Mstar']*dx,  itm['MBH']*dy,  itm['Object'],
    verticalalignment='bottom', horizontalalignment='left',
    color='peru', fontsize=10)

plt_graham, = plt.loglog(M_sph_arr, M_bh_arr, 'bo',  markeredgewidth=0.0, markersize=5)
#plt.loglog(M_sph_arr_GS13_sc, M_bh_arr_GS13_sc, 'ro',  markeredgewidth=0.0, markersize=5, label='GS15 core-Sersic')
#plt.loglog(M_sph_arr_imbh_other, M_bh_arr_imbh_other, 'k+',  markeredgewidth=2.0, markersize=7)
plt_graham_scott, = plt.loglog(M_sph_arr_GS13_s, M_bh_arr_GS13_s, 'go', markeredgewidth=0.0, markersize=5)

plt_fourstar, = plt.loglog(M_sph_arr_imbh_other, M_bh_arr_imbh_other, 'k*',  markeredgewidth=0.0, markersize=10)

yerr = np.array(M_sph_arr_imbh)*0+3e4
xerr = np.array(M_bh_arr_imbh)*0+1e8
#errorbar(M_sph_arr_imbh_confirmed, M_bh_arr_imbh_confirmed, yerr=0, xerr=M_sph_arr_imbh_confirmed_err,fmt='.', ecolor='g', capthick=2)


plt_literature, = plt.loglog(imbh_lit[:,2], imbh_lit[:,1], color='red', linestyle='none', 
    marker='*', markeredgecolor='maroon', markeredgewidth=1.5, alpha=0.5, markersize=17)

plt_imbh, = plt.loglog(M_sph_arr_imbh_confirmed, M_bh_arr_imbh_confirmed, color='green', linestyle='none', 
    marker='*', markeredgecolor='k', markeredgewidth=1.5, alpha=0.5, markersize=17)


plt.loglog(x_borders, line_1, '--', color='gray', lw=2)
#plt.loglog(x_borders2, line_2, 'r')

plt.tick_params(which='major',length=10)
plt.tick_params(which='minor',length=5)

plt.ylabel(r"$M_{\rm BH}$, M$_{\odot}$", fontdict=font)
plt.xlabel(r"$M_{\rm bulge}$, M$_{\odot}$", fontdict=font)

legend_plots = [plt_imbh, plt_literature, plt_fourstar, plt_graham, plt_graham_scott,lit_UCD,lit_cE,lit_other]
legend_labels = ['IMBH (FourStar + HST)', 'IMBH (literature)', 'IMBH candidates (FourStar)', 'Graham et al. 2015', 'Graham & Scott 2015','UCD (literature)','cE (literature)','Other galaxies (literature)']
plt.legend(legend_plots, legend_labels, numpoints=1, loc='upper left', prop={'size': 11})

#plt.xlim(1.5e8,2e12)
plt.xlim(1.5e7,2e12)



plt.savefig('../../paper/diagrams/SR_kcorr_LT.pdf',dpi=300, bbox_inches='tight')
plt.close()
