#!/usr/bin/env python3
#  -*- coding: utf-8 -*-

"""
Reads data of oil spill arrival time from shipping routes to different sites and computes its monthly mean and standard deviation

Author: Thomas Dobbelaere, Earth and Life Institute, UCLouvain, Belgium
Last modified: 9 November 2022
"""
import pandas as pd
import calendar
import matplotlib.pyplot as plt
import numpy as np

months = [calendar.month_abbr[i] for i in range(1,13)]
x = np.arange(12)
routes = ["Bahrain", "Qatar-Iran", 'Ras Laffan to North Field',"Ras Laffan LNG export",'Doha-Mesaieed']
width = 0.18
offset = np.arange(-2,3)*width
cmap = plt.get_cmap("Reds_r")
clrs = cmap(0.1 + 0.8*np.linspace(0,1,5))

df = pd.read_csv("arrival_time_route.csv")
df['month'] = df.month.apply(lambda x: months.index(x))
data_by_route = df.groupby(by=['route'])
means = df.groupby(by=['month','route']).mean()

fig, ax = plt.subplots(figsize=(14,7))

for i,route in enumerate(routes):
    meanv = [means.loc[(i,route),'arrival_time'] for i in range(12)]
    ax.bar(
        x+offset[i], meanv, width=width, color=clrs[i], ecolor='k', capsize=3, label=route
    )
    grp = data_by_route.get_group(route)
    ax.scatter(x[grp.month]+offset[i], grp.arrival_time, s=10, facecolors='none', edgecolors="k")

ax.set_ylabel('Arrival time (days)', fontsize=14)
ax.set_yticks([0,1,2,3,4])
ax.set_ylim(0,5)
ax.set_yticklabels((0,1,2,3,4),fontsize=14)
ax.set_xticks(x)
ax.set_xticklabels(months, fontsize=14)
ax.spines['top'].set_visible(False) 
ax.spines['right'].set_visible(False)
for i in range(1,5):
    ax.axhline(y=i, color='grey', linestyle=(0, (2, 10)))
ax.legend(loc='upper center', fontsize=12,  bbox_to_anchor=(0.5, -0.075), ncol=5)
plt.savefig("barplot_mean_dots.pdf", dpi=300, bbox_inches='tight')