# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # Run this after running `plot_results.ipynb`

from astropy.io import ascii
from astropy.table import Table

# +
charli = Table.read('charli.csv', format='ascii')
charli.rename_column('Star', 'Target')

charli.rename_column('Teff', '$T_\mathrm{eff, MOOG}$')
charli.remove_columns(['N lines Fe I', 'N lines Fe II', 'Trends Plot', 'Notes', 'micro', 'log g', '[Fe I/H]', '[Fe II/H]'])

#charli['[Fe I/H]'] = ["${0}$".format(s.replace('+/-', '\pm')) if hasattr(s, 'replace') else np.nan for s in charli['[Fe I/H]']]
#charli['[Fe II/H]'] = ["${0}$".format(s.replace('+/-', '\pm')) if hasattr(s, 'replace') else np.nan for s in charli['[Fe I/H]']]
# -

charli

# +
# jason = Table.read('/Users/bmmorris/Dropbox/Apps/ShareLaTeX/freckles/jc-notes/Teff-SME.txt', 
#                    comment='#', delimiter=' ', format='ascii.fixed_width_no_header', 
#                    names=['Target', 'N', 'Number', '$T_\mathrm{eff, SME}$', 'T_eff_sme_err', '$\log g$', '$Z$', '$v \sin i$'])
# jason.remove_columns(['N', 'Number', 'T_eff_sme_err'])
# jason['Target'] = [i if i != 'sigDra' else 'sigmaDraconis' for i in jason['Target']]

# +
# jason = Table.read('/Users/bmmorris/Dropbox/Apps/ShareLaTeX/freckles/jc-notes/Teff-SME-p.txt', 
#                    comment='#', delimiter=' ', format='ascii.fixed_width_no_header', 
#                    names=['Target', 'N', 'Number', '$T_\mathrm{eff, SME}$', 'XX', 'T_eff_sme_err', '$\log g$', '$Z$', '$v \sin i$'])
# jason.remove_columns(['N', 'Number', 'T_eff_sme_err'])
# jason['Target'] = [i if i != 'sigDra' else 'sigmaDraconis' for i in jason['Target']]

rows = []
f = open('/Users/bmmorris/Dropbox/Apps/ShareLaTeX/freckles/jc-notes/Teff-SME-p.txt').read().splitlines()

for line in f: 
    if not line.startswith('#'):
        if len(line.split()) == 9:
            star, n0, n1, teff, std, tefferr, logg, z, vsini = line.split()
            row = [star if star != 'sigDra' else 'sigmaDraconis', 
                   "${0:.0f} \pm {1:.0f}$".format(float(teff), float(tefferr)), logg, z, vsini]
            rows.append(row)
            
jason = Table(rows=rows, names=['Target', '$T_\mathrm{eff, SME}$','$\log g$', '$Z$', '$v \sin i$'])

# +
from json import load

star_key = load(open('stars.json'))

spot_stars = Table(rows=[[star, star_key[star][1][0]] for star in star_key], names=['Target', 'Spot'])
# -

data_start = 3
gaia = ascii.read('temperatures/gaia2.tsv', #names='Target,Gmag,Teff_Gaia,Teff_Gaia_lower,Teff_Gaia_upper'.split(','), 
                  data_start=data_start, delimiter='\t')
# spocs2005 = ascii.read('temperatures/spocs2005_temps.tsv', names='Target, Teff_spocs2005'.split(', '), 
#                        data_start=data_start, delimiter='\t')
# spocs2016 = ascii.read('temperatures/spocs2016_temps.tsv', names='Target, Teff_spocs2016'.split(', '), 
#                        data_start=data_start, delimiter='\t')

gb = gaia.group_by('_1')

# +
from astropy.table import vstack
import numpy as np

gaia_dedup = Table(gb.groups[0])

for i in np.arange(1, len(gb.groups)): 
    group = gb.groups[i]
    gaia_dedup.add_row(group[np.argmin(group['Gmag'])])
    #gaia_dedeup = vstack([gaia_dedup, group[np.argmin(group['Gmag'])]], join_type='inner')
# -

# # %matplotlib inline
# import matplotlib.pyplot as plt
np.median(np.sqrt(gaia_dedup['e_BPmag']**2 + gaia_dedup['e_RPmag']**2))

# +
remove_cols = ['_r', 'RA_ICRS', 'e_RA_ICRS', 'DE_ICRS', 'e_DE_ICRS', 'Source', 'Plx', 'e_Plx', 
               'pmRA', 'e_pmRA', 'pmDE', 'e_pmDE', 'Dup', 'FG', 'e_FG', 'Gmag', 'e_Gmag', 'FBP', 
               'e_FBP', 'BPmag', 'e_BPmag', 'FRP', 'e_FRP', 'RPmag', 'e_RPmag', 'RV',  # 'BP-RP', 
               'e_RV', 'AG', 'E(BP-RP)', 'Rad', 'Lum', 'DR2Name', 'SolID', 'RandomI', 'Epoch', 
               'RPlx', 'RADEcor', 'RAPlxcor', 'RApmRAcor', 'RApmDEcor', 'DEPlxcor', 'DEpmRAcor', 
               'DEpmDEcor', 'PlxpmRAcor', 'PlxpmDEcor', 'pmRApmDEcor', 'NAL', 'NAC', 'NgAL', 
               'NbAL', 'gofAL', 'chi2AL', 'epsi', 'sepsi', 'Solved', 'APF', 'WAL', 'pscol', 
               'e_pscol', 'fvarpi', 'MatchObsA', 'Nper', 'amax', 'type', 'MatchObs', 'o_Gmag', 
               'RFG', 'o_BPmag', 'RFBP', 'o_RPmag', 'RFRP', 'E(BR/RP)', 'Mode', 'BP-G', 'G-RP', 
               'o_RV', 'Tefftemp', 'loggtemp', '[Fe/H]temp', 'Var', 'GLON', 'GLAT', 'ELON', 'ELAT', 
               'fPriam', 'b_AG', 'B_AG', 'b_E(BP-RP)', 'B_E(BP-RP)', 'fFLAME', 'b_Rad', 'B_Rad', 
               'b_Lum', 'B_Lum', 'RAJ2000', 'e_RAJ2000', 'DEJ2000', 'e_DEJ2000']
# 'Teff', 'b_Teff', 'B_Teff', 

gaia_dedup.remove_columns(remove_cols)
# -

gaia_dedup.rename_column('_1', 'Target')

gaia_dedup.rename_column('b_Teff', 'Teff_Gaia_lower')
gaia_dedup.rename_column('B_Teff', 'Teff_Gaia_upper')
gaia_dedup.rename_column('Teff', 'Teff_Gaia')

# +
import numpy as np
gaia_teffs = [gaia_dedup['Teff_Gaia'], 
              gaia_dedup['Teff_Gaia']-gaia_dedup['Teff_Gaia_lower'], 
              gaia_dedup['Teff_Gaia_upper']-gaia_dedup['Teff_Gaia']]

gaia_formatted = []
for mid, lower, upper in Table(gaia_teffs, names=['Mid', 'Lower', 'Upper']):
    if isinstance(mid, float):
        gaia_formatted.append('${0:.0f}^{{+{1:.0f}}}_{{-{2:.0f}}}$'.format(mid, upper, lower))
    else: 
        gaia_formatted.append('')
# -

from astropy.table import Column, join
gaia_dedup.remove_columns(['Teff_Gaia', 'Teff_Gaia_lower', 'Teff_Gaia_upper'])
gaia_dedup.add_column(Column(gaia_formatted, '$T_\mathrm{eff,Gaia}$'))
gaia_dedup['Target'] = [s.strip().replace(' ', '').replace('-', '') for s in list(gaia_dedup['Target'])]

# +
gaia_spot = join(gaia_dedup, spot_stars, join_type='outer')

gaia_spot.add_index('Target')

spot_temps = []
for s in gaia_spot['Spot']:
    if isinstance(s, str) and s in gaia_spot['Target']:
        spot_temps.append(gaia_spot.loc[s]['$T_\mathrm{eff,Gaia}$'])
    else: 
        spot_temps.append("")
        
gaia_spot.add_column(Column(spot_temps, '$T_S$'))
gaia_spot.remove_column('Spot')

# +
gaia_spot = join(gaia_spot, jason, keys='Target', join_type='outer')

gaia_spot = join(gaia_spot, charli, keys='Target', join_type='outer')
# -

gaia_spot.colnames

col_order = ['Target', 'BP-RP', '$T_\\mathrm{eff,Gaia}$', '$T_\\mathrm{eff, SME}$', '$T_\\mathrm{eff, MOOG}$', '$\\log g$', '$Z$', '$v \\sin i$', '$T_S$']
gaia_spot = gaia_spot[col_order]

# +
# import sys
# gaia_spot.write(sys.stdout, format='latex')
# -

sinds = Table.read('/Users/bmmorris/git/arces_hk/freckles.tex')
sinds.sort('Target')

sinds['Target'] = [s.strip().replace(' ', '').replace('-', '') for s in sinds['Target']]

sinds.pprint(max_lines=1000)

# +
from astropy.table import hstack

temps_sinds = join(gaia_spot, sinds, join_type='outer', keys='Target')
# -

temps_sinds.pprint(max_lines=1000, max_width=1000)

temps_sinds.sort('$\log R^\prime_\mathrm{HK}$')
temps_sinds.remove_column('Active?')

# +
# names = list(star_key.keys())
# comp_stars = Table([names, ["{0}, {1}".format(star_key[star][0][0], star_key[star][1][0]) for star in names]], names=['Target', 'Comp.'])
# -

fs_table = Table.read('f_S.tex')
fs_table['Target'] = [t.strip().replace(' ', '').replace('-', '') for t in fs_table['Target']]

full_table = join(temps_sinds, fs_table, join_type='outer', keys='Target')
full_table.sort('$\log R^\prime_\mathrm{HK}$')

col_order = ['Target', 'Sp. Type', 'BP-RP', '$T_\\mathrm{eff,Gaia}$', '$T_\\mathrm{eff, SME}$', '$T_\\mathrm{eff, MOOG}$', '$\\log g$', '$Z$', '$v \\sin i$',
             '$S$', '$\\log R^\\prime_\\mathrm{HK}$', '$f_S$'] # '$T_S$', 
full_table = full_table[col_order]

# +
full_table.add_index('Target')

# Remove SB 2
# row = full_table.loc['HD45088']
# full_table.remove_row(row.index)

for star in ['EPIC211928486', 'EPIC211966629', 'KIC9652680']:
    row = full_table.loc[star]
    full_table.remove_row(row.index)
# -

# full_table.remove_row(-1)
# full_table.write('megatable.tex', format='aastex', caption="\label{tab:megatable}", latexdict = {'tabletype': 'deluxetable*'})
full_table.write('/Users/bmmorris/Dropbox/Apps/ShareLaTeX/freckles/megatable.tex', format='aastex', 
                 caption="\label{tab:megatable}", latexdict = {'tabletype': 'deluxetable*', 
                                                               'col_align': 'lcc|ccc|ccc|cc|cc'}, 
                 overwrite=True)

full_table.pprint(max_lines=1000)

# !cat /Users/bmmorris/Dropbox/Apps/ShareLaTeX/freckles/megatable.tex

# +
from astropy.table import Row

rows = []
counter = -1
for star in full_table['Target']:
    if star == 'HD129333': 
        pass
       # star = 'sigmaDraconis'
    
    if (not star in ['KIC9652680'] and star in star_key) or star in ['HATP11']:
        counter += 1 
        if not star == 'HATP11':
            target_temp = full_table.loc[star]['$T_\mathrm{eff,Gaia}$']
            comp1_name = star_key[star][0][0]
            comp1_temp = full_table.loc[comp1_name]['$T_\mathrm{eff,Gaia}$']
            comp2_name = star_key[star][1][0]
            comp2_temp = full_table.loc[comp2_name]['$T_\mathrm{eff,Gaia}$']
        else: 
            target_temp = full_table.loc[star]['$T_\mathrm{eff,Gaia}$']
            comp1_name = "HD5857"
            comp1_temp = full_table.loc[comp1_name]['$T_\mathrm{eff,Gaia}$']
            comp2_name = "GJ705"
            comp2_temp = full_table.loc[comp2_name]['$T_\mathrm{eff,Gaia}$']
            

        delta_t = float(comp1_temp.split('^')[0][1:]) - float(comp2_temp.split('^')[0][1:])
        
        rows.append([star, target_temp, comp1_name, comp1_temp, comp2_name, comp2_temp, int(delta_t)])

comparison_table = Table(rows=rows, names=['Target', '$T_\mathrm{eff, Gaia}$', 'Comp. 1', 
                                           '$T_\mathrm{Q}$', 'Comp. 2', '$T_\mathrm{S}$', '$\Delta T$'])
# -

comparison_table.sort('$T_\mathrm{eff, Gaia}$')

comparison_table.write('/Users/bmmorris/Dropbox/Apps/ShareLaTeX/freckles/comp_table.tex', format='aastex', 
                         caption="\label{tab:comptable}", latexdict = {'tabletype': 'deluxetable*', 
                                                                       'col_align': 'lc|cc|cc|c'}, 
                         overwrite=True)

comparison_table.pprint(max_lines=100)

# +
# fig, ax = plt.subplots(2, 1, figsize=(4, 8))
# ax[0].scatter([floatify(s) for s in full_table['$T_\mathrm{eff,Gaia}$']], 
#            full_table['$T_\mathrm{eff, SME}$'].data, color='k')
# ax[0].set(xlim=[3800, 6200], ylim=[3800, 6200])
# fontsize=14
# ax[0].set_xlabel('$T_\mathrm{eff, Gaia}$', fontsize=fontsize)
# ax[0].set_ylabel('$T_\mathrm{eff, SME}$', fontsize=fontsize)

# ax[1].set_xlabel('$T_\mathrm{eff, Gaia}$', fontsize=fontsize)
# ax[1].set_ylabel('$T_\mathrm{eff, MOOG}$', fontsize=fontsize)

# for axis in ax:
#     for s in ['right', 'top']:
#         axis.spines[s].set_visible(False)
#     axis.grid(ls=':')
#     axis.plot([4000, 6000], [4000, 6000], ls='--', color='k')

# fig.savefig('paper_plots/temperature_comparison.pdf', bbox_inches='tight')

# +
# gaia_dedup.add_index('Target')

# teffs = [float(s.split('^')[0][1:]) for s in full_table['$T_\mathrm{eff,Gaia}$']]
# colors = [gaia_dedup.loc[t]['BP-RP'] for t in full_table['Target']]

# +
# plt.scatter(teffs, colors)
# plt.xlim([3700, 6400])
# plt.ylim([0.5, 2.5])
# plt.xlabel('$T_\mathrm{eff}$')
# plt.ylabel('BP-RP')

# +
# fs = [float(s.split('\pm')[0][1:]) if isinstance(s, str) else 0 for s in full_table['$f_S$']]
# vsini = [float(s) if (isinstance(s, str) and not s == '****') else 0 for s in full_table['$v \sin i$']]

# plt.scatter(vsini, fs)

# +
# comparison_table['Comp. 1'], comparison_table['Comp. 2']

gaia_dedup.add_index('Target')
# -

colors_comp1 = [gaia_dedup.loc[t]['BP-RP'] for t in comparison_table['Comp. 1']]
colors_comp2 = [gaia_dedup.loc[t]['BP-RP'] for t in comparison_table['Comp. 2']]
colors_targets = [gaia_dedup.loc[t]['BP-RP'] for t in comparison_table['Target']]

plt.figure(figsize=(4, 4))
plt.scatter(colors_targets, colors_comp1, color='C0')
plt.scatter(colors_targets, colors_comp2, color='C1')
plt.plot([0.8, 1.7], [0.8, 1.7])
plt.xlabel('Target BP-RP')
plt.ylabel('Comparison BP-RP')

gaia_dedup.sort('BP-RP')

rotation_table = Table.read('rotation_periods.txt', names=['Target', '$P_\mathrm{rot}$ [d]', 'Reference'], delimiter=' ', format='ascii')

rotation_table.sort('$P_\mathrm{rot}$ [d]')
rotation_table.write('/Users/bmmorris/Dropbox/Apps/ShareLaTeX/freckles/rotation_periods.tex', format='aastex', 
                     latexdict={'col_align': 'lcr', 'tabletype': 'deluxetable*'}, 
                     caption="Literature rotation periods. \label{tab:rotation}", overwrite=True)





StarcoderdataJupyterScriptsDedupFiltered