interpolate.py 4.41 KB
Newer Older
eudesyawog's avatar
eudesyawog committed
1 2 3 4 5 6 7 8 9
import os
import numpy as np
import pandas as pd
import scipy as sp
from scipy import sparse, linalg
import seaborn as sns
import matplotlib.pyplot as plt
sns.set()

10
def interpolate_ts (csv,lstBands):
eudesyawog's avatar
eudesyawog committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
    
    ptrn = os.path.basename(csv)
    year = ptrn.split('_')[1]
    outFolder = "./interpolate"
    if not os.path.exists(outFolder):
        os.makedirs(outFolder)

    df = pd.read_csv(csv)

    outdf = None
    ggplot_dic = {}
    for band in lstBands:
        cols = [col for col in df.columns if col.startswith(band) and col.endswith("Mean")]
        cols.sort()
        
eudesyawog's avatar
eudesyawog committed
26
        times = pd.date_range(start="{}0502".format(year), end = "{}1030".format(year), freq='D')
eudesyawog's avatar
eudesyawog committed
27 28 29 30 31 32 33 34 35 36 37 38 39
        dic = {}

        for index, row in df.iterrows():
            lstValues = []
            for j in range(len(times)): # dates
                date = str(times.strftime('{}_%Y%m%d_Mean'.format(band))[j])
                if date in cols: 
                    lstValues.append(row[date])
                else :
                    lstValues.append(np.nan)
            upsampled = pd.Series(lstValues,index=times)
            interpolated = upsampled.interpolate(method='linear',limit_direction='both')
            resampled = interpolated.resample('5D').mean()
eudesyawog's avatar
eudesyawog committed
40
            
eudesyawog's avatar
eudesyawog committed
41 42 43
            dic.setdefault('feat_index',[]).append(index)
            if band == lstBands[0] :
                dic.setdefault('ID',[]).append(row['ID'])
44
                dic.setdefault('Projet',[]).append(row['Projet'])
eudesyawog's avatar
eudesyawog committed
45 46 47 48 49 50 51 52 53 54
                dic.setdefault('Biom_f',[]).append(row['Biom_f'])
                dic.setdefault('Biom_s',[]).append(row['Biom_s'])
                dic.setdefault('Rdt_f',[]).append(row['Rdt_f'])
                dic.setdefault('Rdt_s',[]).append(row['Rdt_s'])
            for idx , value in resampled.items():
                dic.setdefault('{}_{}'.format(band,idx.strftime("%Y%m%d")),[]).append(value)

                ggplot_dic.setdefault('Date',[]).append(idx.strftime("%Y-%m-%d"))
                ggplot_dic.setdefault('Band',[]).append(band)
                ggplot_dic.setdefault('Plot',[]).append(row['ID'])
55
                ggplot_dic.setdefault('Projet',[]).append(row['Projet'])
eudesyawog's avatar
eudesyawog committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
                # ggplot_dic.setdefault('Crop',[]).append(row['Crop'])
                ggplot_dic.setdefault('Sowing',[]).append(row['Sowing'])
                ggplot_dic.setdefault('Harvest',[]).append(row['Harvest'])
                ggplot_dic.setdefault('Value',[]).append(value)
        
        if outdf is None :
            outdf = pd.DataFrame.from_dict(dic)
        else:
            outdf = outdf.merge(pd.DataFrame.from_dict(dic),on='feat_index',how='inner')

    outCSV = os.path.join(outFolder,'{}'.format(ptrn.replace(".csv","_interpolate.csv")))
    outdf = outdf.drop(columns='feat_index')
    outdf.to_csv(outCSV,index=False)

    # To ggplot
    plotCSV = os.path.join(outFolder,'{}'.format(ptrn.replace(".csv","_interpolate_toggplot.csv")))
    ggplot_df = pd.DataFrame.from_dict(ggplot_dic)
    ggplot_df = ggplot_df.loc[ggplot_df.Plot.isin(outdf['ID'])]
    ggplot_df.to_csv(plotCSV,index=False)

if __name__=='__main__':

    csv = "./stats/niakhar_2017_opt_gapf_notree.csv"
79
    interpolate_ts(csv,["B2","B3","B4","B8","B5","B6","B7","B8A","B11","B12","NDVI","NDWI","EVI","MSAVI2","GDVI","CIGreen","CIRedEdge"])
eudesyawog's avatar
eudesyawog committed
80 81

    csv = "./stats/niakhar_2017_radar_notree.csv"
82
    interpolate_ts(csv,["VH","VV"])
eudesyawog's avatar
eudesyawog committed
83 84

    csv = "./stats/niakhar_2018_opt_gapf_notree.csv"
85
    interpolate_ts(csv,["B2","B3","B4","B8","B5","B6","B7","B8A","B11","B12","NDVI","NDWI","EVI","MSAVI2","GDVI","CIGreen","CIRedEdge"])
eudesyawog's avatar
eudesyawog committed
86 87

    csv = "./stats/niakhar_2018_radar_notree.csv"
88 89 90 91 92 93 94 95 96 97 98 99 100
    interpolate_ts(csv,["VH","VV"])

    csv = "./stats/niakhar-serena_2018_opt_gapf_notree.csv"
    interpolate_ts(csv,["B2","B3","B4","B8","B5","B6","B7","B8A","B11","B12","NDVI","NDWI","EVI","MSAVI2","GDVI","CIGreen","CIRedEdge"])

    csv = "./stats/niakhar-serena_2018_radar_notree.csv"
    interpolate_ts(csv,["VH","VV"])

    csv = "./stats/niakhar-simco_2018_opt_gapf_notree.csv"
    interpolate_ts(csv,["B2","B3","B4","B8","B5","B6","B7","B8A","B11","B12","NDVI","NDWI","EVI","MSAVI2","GDVI","CIGreen","CIRedEdge"])

    csv = "./stats/niakhar-simco_2018_radar_notree.csv"
    interpolate_ts(csv,["VH","VV"])
eudesyawog's avatar
eudesyawog committed
101 102

    csv = "./stats/nioro_2018_opt_gapf_notree.csv"
103
    interpolate_ts(csv,["B2","B3","B4","B8","B5","B6","B7","B8A","B11","B12","NDVI","NDWI","EVI","MSAVI2","GDVI","CIGreen","CIRedEdge"])
eudesyawog's avatar
eudesyawog committed
104 105

    csv = "./stats/nioro_2018_radar_notree.csv"
106
    interpolate_ts(csv,["VH","VV"])