#!/usr/bin/env python
# coding: utf-8

from datetime import datetime, timedelta
import smartcarb as sc



def main():

    # start and stop of time series
    start = datetime(2015,1,1,11)
    stop = datetime(2015,11,1,11)
    delta = timedelta(hours=24)


    kind = '2x2 COSMO grid'
    berlin_tracer = 'XCO2_BC'

    # plume definition
    plume_tracer = 'NO2_BC_column' #'XCO2_BV'
    plume_threshold = 2e15 #0.5

    #plume_tracer = 'XCO2_BV'
    #plume_threshold = 0.5

    use_const_emissions = True

    cloud_threshold = 0.01 # 0.01: mask clouds; 1.0: ignore clouds 

    # method
    solver_method = 'ML'
    use_prior = (solver_method == 'MAP')


    noises = [0.5]#, 0.5, 0.7, 1.0]

    for noise in noises:
        for bg_mode in ['model']:#,'model', 'mean']:

            filename = '../../inversion/Berlin_%s_%s_on_grid_%s>%g_noise-%.1f_bg-%s.dat' % (berlin_tracer,
                    solver_method, plume_tracer, plume_threshold, noise, bg_mode)
            print(filename)

            with open(filename, 'w') as outfile:

                outfile.write("""\
# BERLIN %s emissions in kg/s (method: %s with %s)
#
# Instrument noise:     %.1f
# Plume definition:     %s > %e
# Cloud mask:           CLCT < %.2f
# Background method:    %s
#
""" % (berlin_tracer, solver_method, kind, noise, plume_tracer, plume_threshold, cloud_threshold,
    bg_mode)
                )

                outfile.write('UTC\temissions\temissions std\tnumber of pixels\n')

                for time in sc.misc.iter_times(start, stop, delta):
                    print(time)
                    x, x_std, info = sc.inversion.simple_leastsq(time, bg_mode,
                            cloud_threshold, noise, use_prior,
                            plume_tracer, plume_threshold,
                            use_const_emissions
                    )

                    line = '\t'.join([
                        str(time),
                        '%f' % x,
                        '%f' % x_std,
                        '%d' % info['number of pixels']
                    ])
                    outfile.write(line)
                    outfile.write('\n')



if __name__ == '__main__':
    main()
