
from mpl_toolkits.axes_grid1 import ImageGrid

import matplotlib.pyplot as plt
import numpy as np
import pandas
import scipy.stats

def main(cosmo_filename, tccon_filename):

    # load data
    obs = pandas.DataFrame.from_csv(tccon_filename, sep='\t').resample('H').mean()
    obs = obs[('2015-01-01' < obs.index) & (obs.index <= '2016-01-01')]

    obs_values = obs['XCO2 (ppm)']
    obs_errors = obs['XCO2 error (ppm)']

    mod = pandas.DataFrame.from_csv(cosmo_filename, sep='\t').resample('H').mean()
    mod = (
        mod['XCO2_BG_mean'] +
        mod['XCO2_A_mean'] + mod['XCO2_BV_mean'] + mod['XCO2_JV_mean'] +
        mod['XCO2_RA_mean'] - mod['XCO2_GPP_mean']
    )
    return mod
    print(mod.mean())
    #mod[mod.index >= '2015-10-10'] = np.nan


    valids = np.isfinite(mod) & np.isfinite(obs_values)

    reg = scipy.stats.linregress(mod[valids], obs_values[valids])
    x = np.array([390,410])
    y = reg.slope * x + reg.intercept



    # plot
    fig = plt.figure(figsize=(2*6.31, 4.0))
    ax1 = fig.add_axes([0.08, 0.13, 0.55, 0.8])
    ax2 = fig.add_axes([0.72, 0.13, 0.25, 0.8])

    obs.plot(y='XCO2 (ppm)', yerr='XCO2 error (ppm)', label='TCCON', ls='',
            marker='s', markersize=4, ax=ax1)
    mod.plot(label='COSMO', ls='-', ax=ax1)

    ax1.legend()
    ax1.set_xlabel('')
    ax1.set_ylabel('XCO$_2$ (ppm)')
    ax1.set_ylim(390, 410)
    ax1.grid(True)





    ax2.plot(x,y, 'k--', label='[TCCON] = %.1f [COSMO] + %.1f' % (reg.slope, reg.intercept))
    ax2.errorbar(mod[valids], obs_values[valids], obs_errors[valids],
            marker='s', markersize=4, ls='', label='_none_')
    ax2.plot(x, x, '-', color='gray')
    ax2.set_xlabel('COSMO (ppm)')
    ax2.set_ylabel('TCCON (ppm)')

    ax2.set_xlim(390, 410)
    ax2.set_ylim(390, 410)


    text = 'slope: %.2f\nintercept: %.1f ppm\nr-value: %.2f' % (reg.slope, reg.intercept, reg.rvalue)
    ax2.text(391, 409, text, va='top')

    ax2.grid(True)
    #ax2.legend()



    #ax2.set_aspect('equal', 'box')

    return fig, ax1, ax2



if __name__ == '__main__':
    tccon_filename = sys.argv[1]
    cosmo_filename = sys.argv[2]

    main(cosmo_filename, tccon_filename)
