Skip to content
Snippets Groups Projects
analysistool.py 5.04 KiB
Newer Older
Diego Gomes's avatar
Diego Gomes committed
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from datetime import datetime

class AnalysisTool:
    """Compare data from different cropsites by croptype"""
    
    def __init__(self):
        
        self.data = {}
    
    
    def load_cropsite(self, cropsite_object, cropsite_name):
        
        self.data[cropsite_name] = cropsite_object.data
        
        
    def boxplot(self, croptype):
        """Plot relative deltas of different cropsites for a give croptype"""
        
        data = pd.DataFrame(columns=['Date', 'Month', 'Cropsite', 'Delta'])
        
        start_month = 12
        all_months = {}
        
        for cropsite in self.data.keys():
Diego Gomes's avatar
Diego Gomes committed
            if croptype in self.data[cropsite]['cropwise'].keys():
                for season in self.data[cropsite]['cropwise'][croptype]:
                    dates = self.data[cropsite]['cropwise'][croptype][season]['dates']
                    deltas = self.data[cropsite]['cropwise'][croptype][season]['deltas_rel']['MODIS']
                    months = []
                    cropsites = []

                    first_month = dates[0].month
                    if first_month < start_month:
                        start_month = first_month

                    for date in dates:
                        months.append(date.strftime('%b'))
                        cropsites.append(cropsite)

                    df = pd.DataFrame(list(zip(dates, months, cropsites, np.array(deltas)*100)), columns=['Date', 'Month', 'Cropsite', 'Delta'])
                    data = pd.concat([data, df])
Diego Gomes's avatar
Diego Gomes committed
        
        months = []
        
        for i in range(start_month, start_month + 12):
            if i > 12:
                i = i - 12
            month = datetime.strptime(str(i), '%m').strftime('%b')
            if month in data.values:
                months.append(month)
        
        plt.figure(figsize=(10,5))
        axs = sns.boxplot(x='Month', y='Delta', hue='Cropsite', data=data, order=months)
        axs.set_title(croptype)
        axs.set_ylabel('Relative Difference in Latent Heat Flux [%]')
        axs.axhline(0, color='darkgrey', linestyle='--')
        plt.show()
Diego Gomes's avatar
Diego Gomes committed
        
        
    def scatterplot(self, croptype, cropsite='all', combine=True):
        """Plot latent heat values: MODIS vs FLUXNET"""
        
        colors = ['#134e6f', '#ffa822', '#ff6150', '#1ac0c6']
        
        fig, axs = plt.subplots(figsize=(10, 10))
        
        if cropsite != 'all':
            if cropsite in self.data.keys():
                if croptype in self.data[cropsite]['cropwise'].keys():
                    data = self.data[cropsite]['cropwise'][croptype]
                    if combine == True:
                        x, y = [], []
                        for season in data.keys():
                            x += data[season]['values']['MODIS']
                            y += data[season]['values']['FLUXNET']
                        axs.scatter(x, y, alpha=0.1, color=colors[0])
                        z = np.polyfit(x, y, 1)
                        p = np.poly1d(z)
                        plt.plot(x,p(x), color=colors[0], label=cropsite + ' ' + str(list(data.keys())))
                    else:
                        for season in data.keys():
                            x = data[season]['values']['MODIS']
                            y = data[season]['values']['FLUXNET']
                            axs.scatter(x, y, alpha=0.1)
                            z = np.polyfit(x, y, 1)
                            p = np.poly1d(z)
                            plt.plot(x,p(x), label=cropsite + ' ' + str(season))                 
            else:
                raise ValueError('Invalid cropsite')
        else:
            for n, cropsite in enumerate(self.data.keys()):
                if croptype in self.data[cropsite]['cropwise'].keys():
                    data = self.data[cropsite]['cropwise'][croptype]
                    if combine == True:
                        x, y = [], []
                        for season in data.keys():
                            x += data[season]['values']['MODIS']
                            y += data[season]['values']['FLUXNET']
                        axs.scatter(x, y, alpha=0.1, color=colors[n])
                        z = np.polyfit(x, y, 1)
                        p = np.poly1d(z)
                        plt.plot(x,p(x), color=colors[n], label=cropsite + ' ' + str(list(data.keys())))
                    else:
                        for season in data.keys():
                            x = data[season]['values']['MODIS']
                            y = data[season]['values']['FLUXNET']
                            axs.scatter(x, y, alpha=0.1)
                            z = np.polyfit(x, y, 1)
                            p = np.poly1d(z)
                            plt.plot(x,p(x), label=cropsite + ' ' + str(season))
                        
        axs.set_title(croptype)
        axs.set_xlabel('MODIS Latent Heat Flux [W m-2]')
        axs.set_ylabel('FLUXNET Latent Heat Flux [W m-2]')
        plt.legend()
        plt.show()
Diego Gomes's avatar
Diego Gomes committed