# compare SWAT biomass outputs to forage model (CENTURY) biomass

import os
import pandas

hru_csv = r"C:\Users\Ginger\Documents\NatCap\GIS_local\CGIAR\Peru\SWAT_outputs_9.16.16\Run7_No-Grazing_Baseline\hru_output_raw.csv"
hru_df = pandas.read_csv(hru_csv)

lulc_list = ['FESC', 'RYEG']
subb_list = [1, 2, 3, 4, 5, 6, 7, 9]

fields = ['LULC', 'SUB', 'YEAR', 'MON', 'BIOMt_ha']
biom_df = hru_df[fields]

biom_subs = biom_df.loc[biom_df['LULC'].isin(lulc_list)]
biom_subs = biom_subs.loc[biom_subs['SUB'].isin(subb_list)]
biom_subs = biom_subs.drop_duplicates(subset=fields)

# time series generated by CENTURY
timeseries_dir = r"C:\Users\Ginger\Dropbox\NatCap_backup\CGIAR\Peru\Forage_model_results\biomass_time_series_8.25.16"

combined_df_list = []
for sub in subb_list:
    filename = 's{}_zero_sd.csv'.format(sub)
    forage_csv = os.path.join(timeseries_dir, filename)
    forage_df = pandas.read_csv(forage_csv)
    forage_df['biomass_kgha_CENTURY'] = \
                                  forage_df['sub_{}_dead_kgha'.format(sub)] + \
                                  forage_df['sub_{}_green_kgha'.format(sub)]
    forage_df = forage_df[['year', 'month', 'biomass_kgha_CENTURY']]
    swat_df = biom_subs.loc[biom_subs['SUB'] == sub]
    swat_df['biomass_kgha_SWAT'] = swat_df['BIOMt_ha'] * 1000
    df_list = []
    for lulc in swat_df.LULC.unique():
        sub_df = swat_df.loc[swat_df['LULC'] == lulc]
        swat_grouped = sub_df.groupby(['YEAR', 'MON'])
        df_list.append(pandas.DataFrame(
                      {'SWAT_{}_mean'.format(lulc):
                       swat_grouped.biomass_kgha_SWAT.mean()}).reset_index())
        df_list.append(pandas.DataFrame(
                      {'SWAT_{}_std'.format(lulc):
                       swat_grouped.biomass_kgha_SWAT.std()}).reset_index()[
                                                   'SWAT_{}_std'.format(lulc)])
        df_list.append(pandas.DataFrame(
                      {'SWAT_{}_min'.format(lulc):
                       swat_grouped.biomass_kgha_SWAT.min()}).reset_index()[
                                                   'SWAT_{}_min'.format(lulc)])
        df_list.append(pandas.DataFrame(
                      {'SWAT_{}_max'.format(lulc):
                       swat_grouped.biomass_kgha_SWAT.max()}).reset_index()[
                                                   'SWAT_{}_max'.format(lulc)])
    SWAT_df = pandas.concat(df_list, axis=1)
    new_col = SWAT_df.columns.values
    new_col[0] = 'year'
    new_col[1] = 'month'
    SWAT_df.columns = new_col
    combined = pandas.merge(forage_df, SWAT_df, how='inner', on=['year',
                                                                 'month'])
    combined['subbasin'] = sub
    combined_df_list.append(combined)
full_df = pandas.concat(combined_df_list)
save_as = r"C:\Users\Ginger\Dropbox\NatCap_backup\CGIAR\Peru\SWAT_biomass_comparison\time_series_comparison.csv"
full_df.to_csv(save_as)
