import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from astropy.table import Table, join
from os import chdir, system
from scipy.stats import norm as gauss_norm
from sys import argv
from getopt import getopt

# turn off polyfit ranking warnings
import warnings
warnings.filterwarnings('ignore')


def _prepare_pdf_data(means, stds, range, norm=True):
    x_vals = np.linspace(range[0], range[1], 250)
    y_vals = np.zeros_like(x_vals)
    # create and sum all PDF of stellar abundances
    for d_m, d_s in zip(means, stds):
        if np.isfinite([d_m, d_s]).all():
            y_vals += gauss_norm.pdf(x_vals, loc=d_m, scale=d_s)
    # return normalized summed pdf of all stars
    if norm and np.nansum(y_vals) > 0.:
        y_vals = 1. * y_vals/np.nanmax(y_vals)
    return x_vals, y_vals


def _prepare_hist_data(d, bins, range, norm=True):
    heights, edges = np.histogram(d, bins=bins, range=range)
    width = np.abs(edges[0] - edges[1])
    if norm:
        heights = 1.*heights / np.nanmax(heights)
    return edges[:-1], heights, width


def _evaluate_abund_trend_fit(orig, fit, idx, sigma_low, sigma_high):
    # diffence to the original data
    diff = orig - fit
    std_diff = np.nanstd(diff[idx])
    # select data that will be fitted
    idx_outlier = np.logical_or(diff < (-1. * std_diff * sigma_low),
                                diff > (std_diff * sigma_high))
    return np.logical_and(idx, ~idx_outlier)


def fit_abund_trend(p_data, a_data,
                    steps=3, sigma_low=2.5, sigma_high=2.5,
                    order=5, window=10, n_min_perc=10.,func='poly'):

    idx_fit = np.logical_and(np.isfinite(p_data), np.isfinite(a_data))
    data_len = np.sum(idx_fit)

    n_fit_points_prev = np.sum(idx_fit)
    if data_len <= order + 1:
        return None, None
    p_offset = np.nanmedian(p_data)

    for i_f in range(steps):  # number of sigma clipping steps
        if func == 'cheb':
            coef = np.polynomial.chebyshev.chebfit(p_data[idx_fit] - p_offset, a_data[idx_fit], order)
            f_data = np.polynomial.chebyshev.chebval(p_data - p_offset, coef)
        if func == 'legen':
            coef = np.polynomial.legendre.legfit(p_data[idx_fit] - p_offset, a_data[idx_fit], order)
            f_data = np.polynomial.legendre.legval(p_data - p_offset, coef)
        if func == 'poly':
            coef = np.polyfit(p_data[idx_fit] - p_offset, a_data[idx_fit], order)
            f_data = np.poly1d(coef)(p_data - p_offset)
        if func == 'spline':
            coef = splrep(p_data[idx_fit] - p_offset, a_data[idx_fit], k=order, s=window)
            f_data = splev(p_data - p_offset, coef)

        idx_fit = _evaluate_abund_trend_fit(a_data, f_data, idx_fit, sigma_low, sigma_high)
        n_fit_points = np.sum(idx_fit)
        if 100.*n_fit_points/data_len < n_min_perc:
            break
        if n_fit_points == n_fit_points_prev:
            break
        else:
            n_fit_points_prev = n_fit_points

    a_std = np.nanstd(a_data - f_data)
    return [coef, p_offset], a_std


def eval_abund_trend(p_data, m_data, func='poly'):
    coef, p_offset = m_data

    if func == 'cheb':
        f_data = np.polynomial.chebyshev.chebval(p_data - p_offset, coef)
    if func == 'legen':
        f_data = np.polynomial.legendre.legval(p_data - p_offset, coef)
    if func == 'poly':
        f_data = np.poly1d(coef)(p_data - p_offset)
    if func == 'spline':
        f_data = splev(p_data - p_offset, coef)

    return f_data


simulation_dir = '/shared/data-camelot/cotar/'
data_dir_clusters = simulation_dir+'GaiaDR2_open_clusters_2001_GALAH/'

data_dir = '/shared/ebla/cotar/'
USE_DR3 = True
Q_FLAGS = True
P_INDIVIDUAL = False
suffix = ''

if len(argv) > 1:
    # parse input options
    opts, args = getopt(argv[1:], '', ['dr3=', 'suffix=', 'flags=', 'individual='])
    # set parameters, depending on user inputs
    print(opts)
    for o, a in opts:
        if o == '--dr3':
            USE_DR3 = int(a) > 0
        if o == '--suffix':
            suffix += str(a)
        if o == '--flags':
            Q_FLAGS = int(a) > 0
        if o == '--individual':
            P_INDIVIDUAL = int(a) > 0

CG_data = Table.read(data_dir+'clusters/Cantat-Gaudin_2018/members.fits')
tails_data = Table.read(data_dir+'clusters/cluster_tails/members_open_gaia_tails.fits')

# remove cluster members from tails data
print('Cluster members all:', len(CG_data), len(tails_data))
idx_not_in_cluster = np.in1d(tails_data['source_id'], CG_data['source_id'], invert=True)
tails_data = tails_data[idx_not_in_cluster]
print('Cluster members all:', len(CG_data), len(tails_data))

if USE_DR3:
    # cannon_data = Table.read(data_dir+'GALAH_iDR3_main_alpha_190529.fits')
    cannon_data = Table.read(data_dir+'GALAH_iDR3_main_191213.fits')
    fe_col = 'fe_h'
    teff_col = 'teff'
    q_flag = 'flag_sp'
    suffix += '_DR3'
else:
    pass

if Q_FLAGS:
    suffix += '_flag0'

# determine all possible simulation subdirs
chdir(data_dir_clusters)
for cluster_dir in glob('Cluster_orbits_GaiaDR2_*'):
    chdir(cluster_dir)
    print('Working on clusters in ' + cluster_dir)

    for sub_dir in glob('*'):

        current_cluster = '_'.join(sub_dir.split('_')[0:2])
        source_id_cg = CG_data[CG_data['cluster'] == current_cluster]['source_id']
        source_id_tail = tails_data[tails_data['cluster'] == current_cluster]['source_id']
        idx_cg_memb = np.in1d(cannon_data['source_id'], np.array(source_id_cg))
        idx_tail = np.in1d(cannon_data['source_id'], np.array(source_id_tail))

        if '.png' in sub_dir or 'individual-abund' in sub_dir:
            continue

        print(' ')
        print(sub_dir)
        chdir(sub_dir)

        try:
            g_init = Table.read('members_init_galah.csv', format='ascii', delimiter='\t')
            idx_init = np.in1d(cannon_data['source_id'], g_init['source_id'])
        except:
            idx_init = np.full(len(cannon_data), False)

        try:
            g_in_all = Table.read('possible_ejected-step1.csv', format='ascii', delimiter='\t')
            g_in = Table.read('possible_ejected-step1_galah.csv', format='ascii', delimiter='\t')
            # further refinement of results to be plotted here
            g_in_all = g_in_all[np.logical_and(g_in_all['time_in_cluster'] >= 1.,  # [Myr] longest time (of all incarnations) inside cluster
                                               g_in_all['in_cluster_prob'] >= 68.)]  # percentage of reincarnations inside cluster
            g_in = g_in[np.logical_and(g_in['time_in_cluster'] >= 1.,
                                       g_in['in_cluster_prob'] >= 68.)]
            idx_in = np.in1d(cannon_data['source_id'], g_in['source_id'])
            idx_in_no_CG = np.logical_and(idx_in,
                                          np.logical_not(np.in1d(cannon_data['source_id'], CG_data['source_id'])))
        except:
            idx_in = np.full(len(cannon_data), False)
            idx_in_no_CG = np.full(len(cannon_data), False)

        try:
            g_out = Table.read('possible_outside-step1_galah.csv', format='ascii', delimiter='\t')
            # further refinement of results to be plotted here
            g_out = g_out[np.logical_and(g_out['time_in_cluster'] <= 0,
                                         g_out['in_cluster_prob'] <= 0)]
            idx_out = np.in1d(cannon_data['source_id'], g_out['source_id'])
        except:
            idx_out = np.full(len(cannon_data), False)

        chdir('..')

        if np.sum(idx_init) == 0 or np.sum(idx_in) == 0 or np.sum(idx_out) == 0:
            print(' Some Galah lists are missing')

        if USE_DR3:
            abund_cols = [c for c in cannon_data.colnames if '_fe' in c and 'nr_' not in c and 'diff_' not in c and 'e_' not in c and 'Li' not in c and 'alpha' not in c]  # and ('I' in c or 'II' in c or 'III' in c)]
        else:
            abund_cols = [c for c in cannon_data.colnames if '_abund' in c and len(c.split('_')) == 3]

        # abund_cols = ['e_' + cc for cc in abund_cols]
        # rg = (0., 0.35)
        # yt = [0., 0.1, 0.2, 0.3]
        # medfix = '-snr-sigma_'

        abund_cols = ['diff_' + cc for cc in abund_cols]
        rg = (-0.45, 0.45)
        yt = [-0.3, -0.15, 0.0, 0.15, 0.3]
        medfix = '-detrended-snr_'

        # ------------------------------------------------------------------------------
        # NEW: plot with parameter dependency trends
        # ------------------------------------------------------------------------------
        bs = 40

        x_cols_fig = 7
        y_cols_fig = 5

        param_lims = {'snr_c2_iraf': [5, 175], 'age': [0., 14.], 'teff': [3000, 7000], 'logg': [0.0, 5.5], 'fe_h': [-1.2, 0.5]}
        for param in ['snr_c2_iraf']: #list(param_lims.keys()):
            cannon_data['abund_det'] = 0
            cannon_data['abund_det_elems'] = 0
            print('Estimating membership using parameter', param)
            fig, ax = plt.subplots(y_cols_fig, x_cols_fig, figsize=(15, 10))
            for i_c, col in enumerate(abund_cols):
                # print(col)
                x_p = i_c % x_cols_fig
                y_p = int(1. * i_c / x_cols_fig)

                fit_x_param = 'teff'
                cur_abund_col = '_'.join(col.split('_')[1:])

                cannon_data['diff_' + cur_abund_col] = cannon_data[cur_abund_col]

                idx_val = np.isfinite(cannon_data[col])
                if Q_FLAGS:
                    idx_val = np.logical_and(idx_val, cannon_data[q_flag] == 0)

                idx_u1 = np.logical_and(idx_out, idx_val)
                idx_u2 = np.logical_and(idx_init, idx_val)
                idx_u3 = np.logical_and(idx_in, idx_val)
                idx_u4 = np.logical_and(idx_cg_memb, idx_val)
                idx_u5 = np.logical_and(idx_tail, idx_val)

                fit_model, col_std = fit_abund_trend(cannon_data[fit_x_param][idx_u2],
                                                     cannon_data[cur_abund_col][idx_u2],
                                                     order=3, steps=2, func='poly',
                                                     sigma_low=2.5, sigma_high=2.5, n_min_perc=10.)

                if fit_model is not None:
                    cannon_data['diff_' + cur_abund_col] = cannon_data[cur_abund_col] - eval_abund_trend(cannon_data[fit_x_param], fit_model, func='poly')
                else:
                    cannon_data['diff_' + cur_abund_col] = np.nan

                ax[y_p, x_p].scatter(cannon_data[param][idx_u1], cannon_data[col][idx_u1],
                                     lw=0, s=3, color='C2', label='Field')
                ax[y_p, x_p].scatter(cannon_data[param][idx_u2], cannon_data[col][idx_u2],
                                     lw=0, s=3, color='C0', label='Initial')
                ax[y_p, x_p].scatter(cannon_data[param][idx_u3], cannon_data[col][idx_u3],
                                     lw=0, s=3, color='C1', label='Ejected')
                if np.sum(idx_u5) > 0:
                    print('Ejected in tail:', np.sum(np.logical_and(idx_u3, idx_u5)))
                    ax[y_p, x_p].scatter(cannon_data[param][idx_u5], cannon_data[col][idx_u5],
                                         lw=0, s=3, color='C4', label='Tail')

                label_add = ' = {:.0f}, {:.0f}, {:.0f}'.format(np.sum(idx_u1), np.sum(idx_u2), np.sum(idx_u3))
                ax[y_p, x_p].set(xlim=param_lims[param], title=' '.join(col.split('_')[:2]) + label_add,
                                 ylim=rg,
                                 yticks=yt,)
                ax[y_p, x_p].grid(ls='--', alpha=0.2, color='black')

            rg = (-0.6, 0.6)
            idx_val = np.isfinite(cannon_data[teff_col])
            if Q_FLAGS:
                idx_val = np.logical_and(idx_val, cannon_data[q_flag] == 0)

            x_p = -1
            y_p = -1

            idx_u1 = np.logical_and(idx_out, idx_val)
            idx_u2 = np.logical_and(idx_init, idx_val)
            idx_u3 = np.logical_and(idx_in, idx_val)
            idx_u5 = np.logical_and(idx_tail, idx_val)

            sl1 = ax[y_p, x_p].scatter(cannon_data[param][idx_u1], cannon_data[fe_col][idx_u1],
                                 lw=0, s=3, color='C2', label='Field')
            sl2 = ax[y_p, x_p].scatter(cannon_data[param][idx_u2], cannon_data[fe_col][idx_u2],
                                 lw=0, s=3, color='C0', label='Initial')
            sl3 = ax[y_p, x_p].scatter(cannon_data[param][idx_u3], cannon_data[fe_col][idx_u3],
                                 lw=0, s=3, color='C1', label='Ejected')

            fit_model, col_std = fit_abund_trend(cannon_data[param][idx_u2], cannon_data[fe_col][idx_u2],
                                                 order=3, steps=2, sigma_low=2.5, sigma_high=2.5, n_min_perc=10.,
                                                 func='poly')

            if np.sum(idx_u5) > 0:
                sl5 = ax[y_p, x_p].scatter(cannon_data[param][idx_u5], cannon_data[fe_col][idx_u5],
                                     lw=0, s=3, color='C4', label='Tail')
                ax[-1, -3].legend(handles=[sl1, sl1, sl3, sl5])
            else:
                ax[-1, -3].legend(handles=[sl1, sl1, sl3])

            label_add = ' = {:.0f}, {:.0f}, {:.0f}'.format(np.sum(idx_u1), np.sum(idx_u2), np.sum(idx_u3))
            ax[y_p, x_p].set(ylim=rg, title='Fe/H' + label_add, xlim=param_lims[param])
            ax[y_p, x_p].grid(ls='--', alpha=0.2, color='black')

            x_p = -2
            y_p = -1

            ax[y_p, x_p].scatter(cannon_data['age'][idx_u1], cannon_data[param][idx_u1],
                                 lw=0, s=3, color='C2', label='Field')
            ax[y_p, x_p].scatter(cannon_data['age'][idx_u2], cannon_data[param][idx_u2],
                                 lw=0, s=3, color='C0', label='Initial')
            ax[y_p, x_p].scatter(cannon_data['age'][idx_u3], cannon_data[param][idx_u3],
                                 lw=0, s=3, color='C1', label='Ejected')

            if np.sum(idx_u5) > 0:
                ax[y_p, x_p].scatter(cannon_data['age'][idx_u5], cannon_data[param][idx_u5],
                                     lw=0, s=3, color='C4', label='Tail')

            label_add = ' = {:.0f}, {:.0f}, {:.0f}'.format(np.sum(idx_u1), np.sum(idx_u2), np.sum(idx_u3))
            ax[y_p, x_p].set(ylim=param_lims[param], title='age' + label_add, xlim=[0., 14.])
            ax[y_p, x_p].grid(ls='--', alpha=0.2, color='black')

            plt.subplots_adjust(top=0.97, bottom=0.02, left=0.04, right=0.98, hspace=0.3, wspace=0.3)
            # plt.show()
            plt.savefig('p_' + param + '_abundances' + medfix + sub_dir + '' + suffix + '.png', dpi=250)
            plt.close(fig)

    chdir('..')

[((2, 0, 2, 21), 'matplotlib.use', 'matplotlib.use', ({(2, 15, 2, 20): '"""Agg"""'}, {}), "('Agg')", False, 'import matplotlib\n'), ((14, 0, 14, 33), 'warnings.filterwarnings', 'warnings.filterwarnings', ({(14, 24, 14, 32): '"""ignore"""'}, {}), "('ignore')", False, 'import warnings\n'), ((126, 10, 126, 73), 'astropy.table.Table.read', 'Table.read', ({(126, 21, 126, 72): "data_dir + 'clusters/Cantat-Gaudin_2018/members.fits'"}, {}), "(data_dir + 'clusters/Cantat-Gaudin_2018/members.fits')", False, 'from astropy.table import Table, join\n'), ((127, 13, 127, 87), 'astropy.table.Table.read', 'Table.read', ({(127, 24, 127, 86): "data_dir + 'clusters/cluster_tails/members_open_gaia_tails.fits'"}, {}), "(data_dir + 'clusters/cluster_tails/members_open_gaia_tails.fits')", False, 'from astropy.table import Table, join\n'), ((131, 21, 131, 88), 'numpy.in1d', 'np.in1d', (), '', True, 'import numpy as np\n'), ((149, 0, 149, 24), 'os.chdir', 'chdir', ({(149, 6, 149, 23): 'data_dir_clusters'}, {}), '(data_dir_clusters)', False, 'from os import chdir, system\n'), ((150, 19, 150, 51), 'glob.glob', 'glob', ({(150, 24, 150, 50): '"""Cluster_orbits_GaiaDR2_*"""'}, {}), "('Cluster_orbits_GaiaDR2_*')", False, 'from glob import glob\n'), ((18, 13, 18, 49), 'numpy.linspace', 'np.linspace', ({(18, 25, 18, 33): 'range[0]', (18, 35, 18, 43): 'range[1]', (18, 45, 18, 48): '250'}, {}), '(range[0], range[1], 250)', True, 'import numpy as np\n'), ((19, 13, 19, 34), 'numpy.zeros_like', 'np.zeros_like', ({(19, 27, 19, 33): 'x_vals'}, {}), '(x_vals)', True, 'import numpy as np\n'), ((31, 21, 31, 60), 'numpy.histogram', 'np.histogram', (), '', True, 'import numpy as np\n'), ((32, 12, 32, 39), 'numpy.abs', 'np.abs', ({(32, 19, 32, 38): 'edges[0] - edges[1]'}, {}), '(edges[0] - edges[1])', True, 'import numpy as np\n'), ((41, 15, 41, 35), 'numpy.nanstd', 'np.nanstd', ({(41, 25, 41, 34): 'diff[idx]'}, {}), '(diff[idx])', True, 'import numpy as np\n'), ((43, 18, 44, 63), 'numpy.logical_or', 'np.logical_or', ({(43, 32, 43, 67): 'diff < -1.0 * std_diff * sigma_low', (44, 32, 44, 62): 'diff > std_diff * sigma_high'}, {}), '(diff < -1.0 * std_diff * sigma_low, diff > std_diff * sigma_high)', True, 'import numpy as np\n'), ((45, 11, 45, 44), 'numpy.logical_and', 'np.logical_and', ({(45, 26, 45, 29): 'idx', (45, 31, 45, 43): '(~idx_outlier)'}, {}), '(idx, ~idx_outlier)', True, 'import numpy as np\n'), ((53, 15, 53, 30), 'numpy.sum', 'np.sum', ({(53, 22, 53, 29): 'idx_fit'}, {}), '(idx_fit)', True, 'import numpy as np\n'), ((55, 24, 55, 39), 'numpy.sum', 'np.sum', ({(55, 31, 55, 38): 'idx_fit'}, {}), '(idx_fit)', True, 'import numpy as np\n'), ((58, 15, 58, 35), 'numpy.nanmedian', 'np.nanmedian', ({(58, 28, 58, 34): 'p_data'}, {}), '(p_data)', True, 'import numpy as np\n'), ((83, 12, 83, 38), 'numpy.nanstd', 'np.nanstd', ({(83, 22, 83, 37): 'a_data - f_data'}, {}), '(a_data - f_data)', True, 'import numpy as np\n'), ((113, 17, 113, 83), 'getopt.getopt', 'getopt', ({(113, 24, 113, 32): 'argv[1:]', (113, 34, 113, 36): '""""""', (113, 38, 113, 82): "['dr3=', 'suffix=', 'flags=', 'individual=']"}, {}), "(argv[1:], '', ['dr3=', 'suffix=', 'flags=', 'individual='])", False, 'from getopt import getopt\n'), ((137, 18, 137, 68), 'astropy.table.Table.read', 'Table.read', ({(137, 29, 137, 67): "data_dir + 'GALAH_iDR3_main_191213.fits'"}, {}), "(data_dir + 'GALAH_iDR3_main_191213.fits')", False, 'from astropy.table import Table, join\n'), ((151, 4, 151, 22), 'os.chdir', 'chdir', ({(151, 10, 151, 21): 'cluster_dir'}, {}), '(cluster_dir)', False, 'from os import chdir, system\n'), ((154, 19, 154, 28), 'glob.glob', 'glob', ({(154, 24, 154, 27): '"""*"""'}, {}), "('*')", False, 'from glob import glob\n'), ((338, 4, 338, 15), 'os.chdir', 'chdir', ({(338, 10, 338, 14): '""".."""'}, {}), "('..')", False, 'from os import chdir, system\n'), ((52, 29, 52, 48), 'numpy.isfinite', 'np.isfinite', ({(52, 41, 52, 47): 'p_data'}, {}), '(p_data)', True, 'import numpy as np\n'), ((52, 50, 52, 69), 'numpy.isfinite', 'np.isfinite', ({(52, 62, 52, 68): 'a_data'}, {}), '(a_data)', True, 'import numpy as np\n'), ((75, 23, 75, 38), 'numpy.sum', 'np.sum', ({(75, 30, 75, 37): 'idx_fit'}, {}), '(idx_fit)', True, 'import numpy as np\n'), ((91, 17, 91, 73), 'numpy.polynomial.chebyshev.chebval', 'np.polynomial.chebyshev.chebval', ({(91, 49, 91, 66): 'p_data - p_offset', (91, 68, 91, 72): 'coef'}, {}), '(p_data - p_offset, coef)', True, 'import numpy as np\n'), ((93, 17, 93, 71), 'numpy.polynomial.legendre.legval', 'np.polynomial.legendre.legval', ({(93, 47, 93, 64): 'p_data - p_offset', (93, 66, 93, 70): 'coef'}, {}), '(p_data - p_offset, coef)', True, 'import numpy as np\n'), ((167, 8, 167, 22), 'os.chdir', 'chdir', ({(167, 14, 167, 21): 'sub_dir'}, {}), '(sub_dir)', False, 'from os import chdir, system\n'), ((199, 8, 199, 19), 'os.chdir', 'chdir', ({(199, 14, 199, 18): '""".."""'}, {}), "('..')", False, 'from os import chdir, system\n'), ((23, 22, 23, 64), 'scipy.stats.norm.pdf', 'gauss_norm.pdf', (), '', True, 'from scipy.stats import norm as gauss_norm\n'), ((25, 16, 25, 33), 'numpy.nansum', 'np.nansum', ({(25, 26, 25, 32): 'y_vals'}, {}), '(y_vals)', True, 'import numpy as np\n'), ((26, 29, 26, 46), 'numpy.nanmax', 'np.nanmax', ({(26, 39, 26, 45): 'y_vals'}, {}), '(y_vals)', True, 'import numpy as np\n'), ((34, 31, 34, 49), 'numpy.nanmax', 'np.nanmax', ({(34, 41, 34, 48): 'heights'}, {}), '(heights)', True, 'import numpy as np\n'), ((62, 19, 62, 102), 'numpy.polynomial.chebyshev.chebfit', 'np.polynomial.chebyshev.chebfit', ({(62, 51, 62, 77): 'p_data[idx_fit] - p_offset', (62, 79, 62, 94): 'a_data[idx_fit]', (62, 96, 62, 101): 'order'}, {}), '(p_data[idx_fit] - p_offset, a_data[idx_fit],\n    order)', True, 'import numpy as np\n'), ((63, 21, 63, 77), 'numpy.polynomial.chebyshev.chebval', 'np.polynomial.chebyshev.chebval', ({(63, 53, 63, 70): 'p_data - p_offset', (63, 72, 63, 76): 'coef'}, {}), '(p_data - p_offset, coef)', True, 'import numpy as np\n'), ((65, 19, 65, 100), 'numpy.polynomial.legendre.legfit', 'np.polynomial.legendre.legfit', ({(65, 49, 65, 75): 'p_data[idx_fit] - p_offset', (65, 77, 65, 92): 'a_data[idx_fit]', (65, 94, 65, 99): 'order'}, {}), '(p_data[idx_fit] - p_offset, a_data[idx_fit],\n    order)', True, 'import numpy as np\n'), ((66, 21, 66, 75), 'numpy.polynomial.legendre.legval', 'np.polynomial.legendre.legval', ({(66, 51, 66, 68): 'p_data - p_offset', (66, 70, 66, 74): 'coef'}, {}), '(p_data - p_offset, coef)', True, 'import numpy as np\n'), ((68, 19, 68, 81), 'numpy.polyfit', 'np.polyfit', ({(68, 30, 68, 56): 'p_data[idx_fit] - p_offset', (68, 58, 68, 73): 'a_data[idx_fit]', (68, 75, 68, 80): 'order'}, {}), '(p_data[idx_fit] - p_offset, a_data[idx_fit], order)', True, 'import numpy as np\n'), ((95, 17, 95, 32), 'numpy.poly1d', 'np.poly1d', ({(95, 27, 95, 31): 'coef'}, {}), '(coef)', True, 'import numpy as np\n'), ((159, 56, 159, 78), 'numpy.array', 'np.array', ({(159, 65, 159, 77): 'source_id_cg'}, {}), '(source_id_cg)', True, 'import numpy as np\n'), ((160, 53, 160, 77), 'numpy.array', 'np.array', ({(160, 62, 160, 76): 'source_id_tail'}, {}), '(source_id_tail)', True, 'import numpy as np\n'), ((170, 21, 170, 89), 'astropy.table.Table.read', 'Table.read', (), '', False, 'from astropy.table import Table, join\n'), ((171, 23, 171, 77), 'numpy.in1d', 'np.in1d', ({(171, 31, 171, 55): "cannon_data['source_id']", (171, 57, 171, 76): "g_init['source_id']"}, {}), "(cannon_data['source_id'], g_init['source_id'])", True, 'import numpy as np\n'), ((176, 23, 176, 95), 'astropy.table.Table.read', 'Table.read', (), '', False, 'from astropy.table import Table, join\n'), ((177, 19, 177, 97), 'astropy.table.Table.read', 'Table.read', (), '', False, 'from astropy.table import Table, join\n'), ((183, 21, 183, 73), 'numpy.in1d', 'np.in1d', ({(183, 29, 183, 53): "cannon_data['source_id']", (183, 55, 183, 72): "g_in['source_id']"}, {}), "(cannon_data['source_id'], g_in['source_id'])", True, 'import numpy as np\n'), ((191, 20, 191, 98), 'astropy.table.Table.read', 'Table.read', (), '', False, 'from astropy.table import Table, join\n'), ((195, 22, 195, 75), 'numpy.in1d', 'np.in1d', ({(195, 30, 195, 54): "cannon_data['source_id']", (195, 56, 195, 74): "g_out['source_id']"}, {}), "(cannon_data['source_id'], g_out['source_id'])", True, 'import numpy as np\n'), ((232, 22, 232, 76), 'matplotlib.pyplot.subplots', 'plt.subplots', (), '', True, 'import matplotlib.pyplot as plt\n'), ((281, 22, 281, 56), 'numpy.isfinite', 'np.isfinite', ({(281, 34, 281, 55): 'cannon_data[teff_col]'}, {}), '(cannon_data[teff_col])', True, 'import numpy as np\n'), ((288, 21, 288, 53), 'numpy.logical_and', 'np.logical_and', ({(288, 36, 288, 43): 'idx_out', (288, 45, 288, 52): 'idx_val'}, {}), '(idx_out, idx_val)', True, 'import numpy as np\n'), ((289, 21, 289, 54), 'numpy.logical_and', 'np.logical_and', ({(289, 36, 289, 44): 'idx_init', (289, 46, 289, 53): 'idx_val'}, {}), '(idx_init, idx_val)', True, 'import numpy as np\n'), ((290, 21, 290, 52), 'numpy.logical_and', 'np.logical_and', ({(290, 36, 290, 42): 'idx_in', (290, 44, 290, 51): 'idx_val'}, {}), '(idx_in, idx_val)', True, 'import numpy as np\n'), ((291, 21, 291, 54), 'numpy.logical_and', 'np.logical_and', ({(291, 36, 291, 44): 'idx_tail', (291, 46, 291, 53): 'idx_val'}, {}), '(idx_tail, idx_val)', True, 'import numpy as np\n'), ((333, 12, 333, 101), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', (), '', True, 'import matplotlib.pyplot as plt\n'), ((335, 12, 335, 104), 'matplotlib.pyplot.savefig', 'plt.savefig', (), '', True, 'import matplotlib.pyplot as plt\n'), ((336, 12, 336, 26), 'matplotlib.pyplot.close', 'plt.close', ({(336, 22, 336, 25): 'fig'}, {}), '(fig)', True, 'import matplotlib.pyplot as plt\n'), ((22, 11, 22, 34), 'numpy.isfinite', 'np.isfinite', ({(22, 23, 22, 33): '[d_m, d_s]'}, {}), '([d_m, d_s])', True, 'import numpy as np\n'), ((69, 21, 69, 36), 'numpy.poly1d', 'np.poly1d', ({(69, 31, 69, 35): 'coef'}, {}), '(coef)', True, 'import numpy as np\n'), ((201, 11, 201, 27), 'numpy.sum', 'np.sum', ({(201, 18, 201, 26): 'idx_init'}, {}), '(idx_init)', True, 'import numpy as np\n'), ((201, 36, 201, 50), 'numpy.sum', 'np.sum', ({(201, 43, 201, 49): 'idx_in'}, {}), '(idx_in)', True, 'import numpy as np\n'), ((201, 59, 201, 74), 'numpy.sum', 'np.sum', ({(201, 66, 201, 73): 'idx_out'}, {}), '(idx_out)', True, 'import numpy as np\n'), ((243, 26, 243, 55), 'numpy.isfinite', 'np.isfinite', ({(243, 38, 243, 54): 'cannon_data[col]'}, {}), '(cannon_data[col])', True, 'import numpy as np\n'), ((247, 25, 247, 57), 'numpy.logical_and', 'np.logical_and', ({(247, 40, 247, 47): 'idx_out', (247, 49, 247, 56): 'idx_val'}, {}), '(idx_out, idx_val)', True, 'import numpy as np\n'), ((248, 25, 248, 58), 'numpy.logical_and', 'np.logical_and', ({(248, 40, 248, 48): 'idx_init', (248, 50, 248, 57): 'idx_val'}, {}), '(idx_init, idx_val)', True, 'import numpy as np\n'), ((249, 25, 249, 56), 'numpy.logical_and', 'np.logical_and', ({(249, 40, 249, 46): 'idx_in', (249, 48, 249, 55): 'idx_val'}, {}), '(idx_in, idx_val)', True, 'import numpy as np\n'), ((250, 25, 250, 61), 'numpy.logical_and', 'np.logical_and', ({(250, 40, 250, 51): 'idx_cg_memb', (250, 53, 250, 60): 'idx_val'}, {}), '(idx_cg_memb, idx_val)', True, 'import numpy as np\n'), ((251, 25, 251, 58), 'numpy.logical_and', 'np.logical_and', ({(251, 40, 251, 48): 'idx_tail', (251, 50, 251, 57): 'idx_val'}, {}), '(idx_tail, idx_val)', True, 'import numpy as np\n'), ((283, 26, 283, 75), 'numpy.logical_and', 'np.logical_and', ({(283, 41, 283, 48): 'idx_val', (283, 50, 283, 74): 'cannon_data[q_flag] == 0'}, {}), '(idx_val, cannon_data[q_flag] == 0)', True, 'import numpy as np\n'), ((304, 15, 304, 29), 'numpy.sum', 'np.sum', ({(304, 22, 304, 28): 'idx_u5'}, {}), '(idx_u5)', True, 'import numpy as np\n'), ((311, 59, 311, 73), 'numpy.sum', 'np.sum', ({(311, 66, 311, 72): 'idx_u1'}, {}), '(idx_u1)', True, 'import numpy as np\n'), ((311, 75, 311, 89), 'numpy.sum', 'np.sum', ({(311, 82, 311, 88): 'idx_u2'}, {}), '(idx_u2)', True, 'import numpy as np\n'), ((311, 91, 311, 105), 'numpy.sum', 'np.sum', ({(311, 98, 311, 104): 'idx_u3'}, {}), '(idx_u3)', True, 'import numpy as np\n'), ((325, 15, 325, 29), 'numpy.sum', 'np.sum', ({(325, 22, 325, 28): 'idx_u5'}, {}), '(idx_u5)', True, 'import numpy as np\n'), ((329, 59, 329, 73), 'numpy.sum', 'np.sum', ({(329, 66, 329, 72): 'idx_u1'}, {}), '(idx_u1)', True, 'import numpy as np\n'), ((329, 75, 329, 89), 'numpy.sum', 'np.sum', ({(329, 82, 329, 88): 'idx_u2'}, {}), '(idx_u2)', True, 'import numpy as np\n'), ((329, 91, 329, 105), 'numpy.sum', 'np.sum', ({(329, 98, 329, 104): 'idx_u3'}, {}), '(idx_u3)', True, 'import numpy as np\n'), ((179, 32, 180, 82), 'numpy.logical_and', 'np.logical_and', ({(179, 47, 179, 80): "(g_in_all['time_in_cluster'] >= 1.0)", (180, 47, 180, 81): "(g_in_all['in_cluster_prob'] >= 68.0)"}, {}), "(g_in_all['time_in_cluster'] >= 1.0, g_in_all[\n    'in_cluster_prob'] >= 68.0)", True, 'import numpy as np\n'), ((181, 24, 182, 70), 'numpy.logical_and', 'np.logical_and', ({(181, 39, 181, 68): "(g_in['time_in_cluster'] >= 1.0)", (182, 39, 182, 69): "(g_in['in_cluster_prob'] >= 68.0)"}, {}), "(g_in['time_in_cluster'] >= 1.0, g_in['in_cluster_prob'] >= 68.0)", True, 'import numpy as np\n'), ((185, 57, 185, 112), 'numpy.in1d', 'np.in1d', ({(185, 65, 185, 89): "cannon_data['source_id']", (185, 91, 185, 111): "CG_data['source_id']"}, {}), "(cannon_data['source_id'], CG_data['source_id'])", True, 'import numpy as np\n'), ((193, 26, 194, 71), 'numpy.logical_and', 'np.logical_and', ({(193, 41, 193, 70): "(g_out['time_in_cluster'] <= 0)", (194, 41, 194, 70): "(g_out['in_cluster_prob'] <= 0)"}, {}), "(g_out['time_in_cluster'] <= 0, g_out['in_cluster_prob'] <= 0)", True, 'import numpy as np\n'), ((245, 30, 245, 79), 'numpy.logical_and', 'np.logical_and', ({(245, 45, 245, 52): 'idx_val', (245, 54, 245, 78): 'cannon_data[q_flag] == 0'}, {}), '(idx_val, cannon_data[q_flag] == 0)', True, 'import numpy as np\n'), ((269, 19, 269, 33), 'numpy.sum', 'np.sum', ({(269, 26, 269, 32): 'idx_u5'}, {}), '(idx_u5)', True, 'import numpy as np\n'), ((274, 63, 274, 77), 'numpy.sum', 'np.sum', ({(274, 70, 274, 76): 'idx_u1'}, {}), '(idx_u1)', True, 'import numpy as np\n'), ((274, 79, 274, 93), 'numpy.sum', 'np.sum', ({(274, 86, 274, 92): 'idx_u2'}, {}), '(idx_u2)', True, 'import numpy as np\n'), ((274, 95, 274, 109), 'numpy.sum', 'np.sum', ({(274, 102, 274, 108): 'idx_u3'}, {}), '(idx_u3)', True, 'import numpy as np\n'), ((270, 53, 270, 83), 'numpy.logical_and', 'np.logical_and', ({(270, 68, 270, 74): 'idx_u3', (270, 76, 270, 82): 'idx_u5'}, {}), '(idx_u3, idx_u5)', True, 'import numpy as np\n')]