%matplotlib inline
%config InlineBackend.figure_format='retina'

import warnings
warnings.filterwarnings("ignore")

"""
Explanation: ApJdataFrames Slesnick2006
Title: A LARGE-AREA SEARCH FOR LOW-MASS OBJECTS IN UPPER SCORPIUS. I. THE PHOTOMETRIC CAMPAIGN AND NEW BROWN DWARFS 
Authors: CATHERINE L. SLESNICK, JOHN M. CARPENTER, AND LYNNE A. HILLENBRAND  
Data is from this paper:
http://iopscience.iop.org/1538-3881/131/6/3016/fulltext/205148.html
End of explanation
"""


import pandas as pd

names = ["ID","R","I","J","H","KS","TiO_7140","TiO_8465","NaI_8189","Spectral Type","EW_Ha","Gravity"]
tbl1 = pd.read_csv("http://iopscience.iop.org/1538-3881/131/6/3016/fulltext/205148.tb1.txt",
                   sep='\t', names=names, skip_blank_lines=True, na_values='\ldots')
tbl1.head()

"""
Explanation: Table 1- Measured Quantities for PMS Candidates with Observed Spectra
End of explanation
"""


names = ["ID","MJ","AV","log_Teff","log_L_bol"]
tbl2 = pd.read_csv("http://iopscience.iop.org/1538-3881/131/6/3016/fulltext/205148.tb2.txt",
                   sep='\t', names=names, skip_blank_lines=True, na_values='\ldots')
tbl2.head()

"""
Explanation: Table 2 - Derived Quantities for New USco Members
End of explanation
"""


tbl1.to_csv("../data/Slesnick2006/tbl1.csv", sep="\t", index=False)
tbl2.to_csv("../data/Slesnick2006/tbl2.csv", sep="\t", index=False)

"""
Explanation: Save the data tables locally.
mkdir ../data/Slesnick2006
End of explanation
"""


%matplotlib inline
import seaborn as sns
import matplotlib.pyplot as plt

import gully_custom

SpT, _, _, _ = gully_custom.specTypePlus(tbl1["Spectral Type"])

"""
Explanation: Make a plot
End of explanation
"""


EW_NaI_8189 = (1.0 - tbl1.NaI_8189.values)*30.0

c = 'Dwarf'
i = tbl1.Gravity.values == c
plt.plot(SpT[i], EW_NaI_8189[i], '.', label = c)
c = 'USco'
i = tbl1.Gravity.values == c
plt.plot(SpT[i], EW_NaI_8189[i], '.', label = c)

c = 'Int'
i = tbl1.Gravity.values == c
plt.plot(SpT[i], EW_NaI_8189[i], '.', label = c)

plt.legend(loc='best')
plt.xlim(0, 15)
plt.ylim(-5, 8.5)

EW_NaI_8189[tbl1.Gravity.values == 'USco']

"""
Explanation: Turn the ratio into an equivalent width:
$EW = (1 - \frac{F_{\lambda_{8189}}}{F_{\lambda_{8150}}})\Delta \lambda$
End of explanation
"""


from astroquery.simbad import Simbad
import astropy.coordinates as coord
import astropy.units as u

customSimbad.list_votable_fields()

bands = ['U','B','V','R','I','J','H','K','u','g','r','i','z']
fluxes = ['fluxdata({})'.format(band) for band in bands]
flux_cols = sum([['FLUX_{}'.format(band), 'FLUX_ERROR_{}'.format(band)] for band in bands], [])

customSimbad = Simbad()
customSimbad.add_votable_fields('otype', 'id', 'sptype', 'flux(U)','flux_error(U)''flux(B)','flux_error(B)''flux(V)','flux_error(V)''flux(R)','flux_error(R)''flux(I)','flux_error(I)''flux(J)','flux_error(J)''flux(H)','flux_error(H)''flux(K)','flux_error(K)''flux(u)','flux_error(u)''flux(g)','flux_error(g)''flux(r)','flux_error(r)''flux(i)','flux_error(i)''flux(z)','flux_error(z)')

"""
Explanation: Match the sources to SIMBAD
This will make it easier to get the coordinates, and query other properties.
End of explanation
"""


input_to_simbad = "[SCH2006] J"+tbl2.ID.str.strip("SCH ")

result = customSimbad.query_objects(input_to_simbad, verbose=True)

result.columns

result[flux_cols][0:5]

print "There were {} sources queried, and {} sources found.".format(len(input_to_simbad), len(result))
if len(input_to_simbad) == len(result):
    print "Hooray!  Everything matched"
else:
    print "Which ones were not found?"

"""
Explanation: SCH is a non-standard input for Simbad.  Need to put in the 2MASS coordinates.
End of explanation
"""


tbl2["Simbad_name"] = input_to_simbad
result["Simbad_name"] = input_to_simbad
simbad_df = result.to_pandas()
del simbad_df["ID"]

tbl2_simbad = pd.merge(tbl2, simbad_df, on="Simbad_name")
tbl2_simbad.columns

tbl2_simbad[[u'MAIN_ID', u'ID', u'RA', u'DEC', u'MJ', u'AV', u'log_Teff', u'log_L_bol',u'OTYPE',
             u'SP_TYPE', u'SP_BIBCODE']].head()

tbl2_simbad.to_csv("../data/Slesnick2006/tbl2_plusSimbad.csv", index=False)

"""
Explanation: Merge the catalogs
End of explanation
"""


