

"""\
Count the number of pixels in plume from Berlin and power plants
for each Level-2 product.

Thresholdes:
    - XCO2 > 0.1 ppm
    - NO2  > 0.2e15 cm-2
    - CO   > 0.8e17 cm-2

Clouds:
    - CLCT < 0.01 (for all gases)
    - CLCT < 0.30 (for NO2)
"""

from datetime import datetime
import os
import sys

from skimage import measure
import numpy as np
import pandas
import smartcarb as sc


def check_overpass(filename):
    """\
    """

    lon_o, lat_o = 13.407696, 52.516984


    time = datetime.strptime(
        os.path.basename(filename).split('_')[3], '%Y%m%d%H'
    )
    tracers = [
        'longitude', 'latitude',
        'XCO2_BV', 'NO2_BV', 'CO_BV',
    ]
    lon, lat, xco2_bv, no2_bv, co_bv, clct = sc.io.read_fields(
        filename, tracers + ['CLCT'],
        time=time, correct_berlin=True
    )

    values = []

    for tracer, thr, cloud_thr in [
            [xco2_bv, 0.1,    0.01],
            [no2_bv,  0.2e15, 0.01],
            [no2_bv,  0.2e15, 0.3],
            [co_bv,   0.8e17, 0.01],
        ]:

        # find plume by signal (ignoring clouds)
        is_plume = sc.plume.find_plume_by_signal(tracer, thr, lon_o, lat_o,
                lon, lat, dn=30, clouds=clct, cloud_thr=cloud_thr)

        value = np.sum(is_plume)
        values.append(value)

    return np.array(values, dtype=int)





def main(out_filename, filenames):

    headers = [
        'filename',
        'XCO2',         #'XCO2_JV > 0.1'
        'NO2(1%)',  #'NO2_JV > 0.2e15 (1%)',
        'NO2(30%)', #'NO2_JV > 0.2e15 (30%)',
        'CO',        #'CO_JV > 0.8e17'
    ]

    with open(out_filename, 'w') as out:

        out.write('\t'.join(headers))
        out.write('\n')

        for filename in sorted(filenames):
            fn = os.path.basename(filename)
            print(fn)
            values = check_overpass(filename)

            if np.sum(values) > 0:
                line = '\t'.join([fn]+[str(v) for v in values])
                out.write(line)
                out.write('\n')


if __name__ == '__main__':
    main('pixels_in_Berlin_plumes_clouds.dat', sys.argv[1:])





